int.Parse: Convert Strings to IntegersConvert strings into ints with the int.Parse and int.TryParse methods.
This page was last reviewed on Nov 25, 2023.
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.
int, uint
Parse example. Here is the int.Parse method. This is the simplest one. Parse() throws exceptions on invalid input. This can be slow if errors are common.
Part 1 Here we have a string containing 3 digit characters—it is not a number, but a number encoded within a string.
Part 2 We pass the 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);
Errors. The int.Parse method is strict. With an invalid string, it throws a FormatException. We can catch this using a try-catch construct.
But Using the 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.
Info TryParse uses somewhat more confusing syntax. It does not throw exceptions.
Detail We must describe the second parameter with the out modifier. TryParse also returns true or false based on its success.
true, false
Detail 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 if. Usually 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).
Tip This removes a branch in our code—we can just use the result, not test it. Branches are good for trees, but bad for performance.
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);
TryParse, new out syntax. We 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); }
Convert. Convert.ToInt32 (along with its siblings Convert.ToInt16 and Convert.ToInt64) is a static wrapper method for the int.Parse method.
Warning ToInt32 can be slower than int.Parse if the surrounding code is equivalent.
Detail The syntax here may be more confusing. It uses the bit size of the 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);
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.
Note The 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
Benchmark, invalid strings. When I first wrote about int.Parse, I recommended it as the best parsing option. After many years, I have changed my mind.
Detail I recommend using TryParse in most situations. It is faster on errors, and is a good default choice for parsing.
Version 1 This version of the code uses int.Parse to parse an invalid number string. It causes an exception on each iteration.
Version 2 Here we use int.TryParse to parse an invalid number string. No exception-handling is needed.
Result On .NET 5 in 2021, using 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
Benchmark, IntParseFast. An optimized int.Parse method reduces computational complexity. It uses a for-loop on the characters in a string.
Info This algorithm maintains the running total as its iterates. The char "1" is offset +48 from the integer 1 in ASCII.
Version 1 This version of the code uses the IntParseFast method to get characters from the string and convert them to an int.
Version 2 Here we just call int.Parse from .NET. This version supports more number formats.
Result On .NET 5 (in 2021, running Linux) 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
A review. Programmers can write their own integer conversion routines—but this is complicated. With Parse and TryParse, .NET helps solve the parsing problem.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 25, 2023 (simplify).
© 2007-2024 Sam Allen.