Parse
, int
The C# int.Parse
and TryParse
methods convert strings to ints. Consider the string
"100": it can be represented as an int
, with no loss of information.
With TryParse
, we use an out
-parameter. This requires the "out" keyword. Usually calling TryParse
is worthwhile—it makes a program sturdier and more reliable.
Parse
exampleHere is the int.Parse
method. This is the simplest one. Parse()
throws exceptions on invalid input. This can be slow if errors are common.
string
containing 3 digit characters—it is not a number, but a number encoded within a string
.string
to int.Parse
(a static
method). Parse()
returns an integer upon success.using System; // Part 1: string containing number. string text = "500"; // Part 2: pass string to int.Parse. int num = int.Parse(text); Console.WriteLine(num);500
The int.Parse
method is strict. With an invalid string
, it throws a FormatException
. We can catch this using a try-catch
construct.
int.TryParse
method is usually a better solution. TryParse
is faster.using System; string input = "carrot"; // ... This will throw an exception. int carrots = int.Parse(input); Console.WriteLine(carrots);Unhandled Exception: System.FormatException: Input string was not in a correct format. at System.Number.StringToNumber(String str, NumberStyles options, ... at System.Number.ParseInt32(String s, NumberStyles style, ...
TryParse
A useful method for parsing integers is the int.TryParse
method. The parsing logic in TryParse
is the same. But the way we call it is different.
TryParse
uses somewhat more confusing syntax. It does not throw exceptions.TryParse
also returns true or false based on its success.TryParse
never throws an exception—even on invalid input and null
. This method is ideal for input that is not always correct.using System; // See if we can parse the string. string text1 = "x"; int num1; bool res = int.TryParse(text1, out num1); if (res == false) { // String is not a number. } // Use int.TryParse on a valid numeric string. string text2 = "10000"; int num2; if (int.TryParse(text2, out num2)) { // It was assigned. } // Display both results. Console.WriteLine(num1); Console.WriteLine(num2);0 10000
TryParse
with no ifUsually we call int.TryParse
inside an if
-statement. But this is not required. And sometimes, we can just treat a failed parse as the default value (0 for int
).
using System; string error = "Welcome"; // This will leave the result variable with a value of 0. int result; int.TryParse(error, out result); Console.WriteLine(result);0
TryParse
, new out syntaxWe can place the "out int
" keywords directly inside a method call. Older versions of C# do not allow this syntax. But this can reduce the line count of a program.
using System; const string value = "345"; // We can place the "out int" declaration in the method call. if (int.TryParse(value, out int result)) { Console.WriteLine(result + 1); }346
Convert.ToInt32
(along with its siblings Convert.ToInt16
and Convert.ToInt64
) is a static
wrapper method for the int.Parse
method.
ToInt32
can be slower than int.Parse
if the surrounding code is equivalent.int
, which may not be relevant to the code's intent.using System; // Convert "text" string to an integer with Convert.ToInt32. string text = "500"; int num = Convert.ToInt32(text); Console.WriteLine(num);500
DateTime
Parsing is fun. It is one of my passions in life. We can parse a string
into a DateTime
type with TryParse
. Parsing methods on DateTime
use a similar syntax.
Parse
and TryParse
methods have separate implementations for each type. But they have a unified calling syntax.using System; string now = "1/22/2017"; // Use TryParse on the DateTime type to parse a date. DateTime parsed; if (DateTime.TryParse(now, out parsed)) { Console.WriteLine(parsed); }1/22/2017 12:00:00 AM
When I first wrote about int.Parse
, I recommended it as the best parsing option. After many years, I have changed my mind.
TryParse
in most situations. It is faster on errors, and is a good default choice for parsing.int.Parse
to parse an invalid number string
. It causes an exception on each iteration.int.TryParse
to parse an invalid number string
. No exception-handling is needed.int.TryParse
on invalid input is many times faster. This can be noticeable in real programs.using System; using System.Diagnostics; const int _max = 10000; // Version 1: parse an invalid string with exception handling. var s1 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { int result; try { result = int.Parse("abc"); } catch { result = 0; } } s1.Stop(); // Version 2: parse an invalid string with TryParse. var s2 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { int result; int.TryParse("abc", out result); } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns"));13243.34 ns int.Parse 15.46 ns int.TryParse
IntParseFast
An optimized int.Parse
method reduces computational complexity. It uses a for
-loop on the characters in a string
.
char
"1" is offset +48 from the integer 1 in ASCII.IntParseFast
method to get characters from the string
and convert them to an int
.int.Parse
from .NET. This version supports more number formats.IntParseFast
is faster, but int.Parse
has been optimized. The difference is smaller than before.using System; using System.Diagnostics; class Program { public static int IntParseFast(string value) { // An optimized int parse method. int result = 0; for (int i = 0; i < value.Length; i++) { result = 10 * result + (value[i] - 48); } return result; } const int _max = 1000000; static void Main() { // Test the methods. Console.WriteLine(IntParseFast("123456")); Console.WriteLine(int.Parse("123456")); var s1 = Stopwatch.StartNew(); // Version 1: use custom parsing algorithm. for (int i = 0; i < _max; i++) { int result = IntParseFast("123456"); } s1.Stop(); var s2 = Stopwatch.StartNew(); // Version 2: use int.Parse. for (int i = 0; i < _max; i++) { int result = int.Parse("123456"); } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); } }123456 123456 3.76 ns: IntParseFast 20.31 ns: int.Parse
Programmers can write their own integer conversion routines—but this is complicated. With Parse
and TryParse
, .NET helps solve the parsing problem.