Home
Search
C# int.Parse: Convert Strings to IntegersConvert strings into ints with the int.Parse and int.TryParse methods.
dot net perls
Parse, int. In C# we can convert a string to an int. Consider the string "100": it can be represented in just a 4 byte int. We use int.Parse and TryParse.
Method notes. With TryParse, we use an out-parameter. 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.
C# program that uses int.Parse
using System; class Program { static void Main() { // Part 1: string containing number. string text = "500"; // Part 2: pass string to int.Parse. int num = int.Parse(text); Console.WriteLine(num); } }
500
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.
C# program that encounters FormatException
using System; class Program { static void Main() { 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.
Out We must describe the second parameter with the out modifier. TryParse also returns true or false based on its success.
Out
True, False
Null TryParse never throws an exception—even on invalid input and null. This method is ideal for input that is not always correct.
C# program that uses int.TryParse
using System; class Program { static void Main() { // 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.
C# program that uses int.TryParse, no if
using System; class Program { static void Main() { 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 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.
C# program that uses TryParse, new out syntax
using System; class Program { static void Main() { 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. Convert.ToInt32 (along with its siblings Convert.ToInt16 and Convert.ToInt64) is a static wrapper method for the int.Parse method.
Static
Warning ToInt32 can be slower than int.Parse if the surrounding code is equivalent.
Confusing 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.
C# program that uses Convert.ToInt32
using System; class Program { static void Main() { // 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.
DateTime.Parse
Note The Parse and TryParse methods have separate implementations for each type. But they have a unified calling syntax.
C# program that calls TryParse on DateTime
using System; class Program { static void Main() { 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.
TryParse 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.
C# program that benchmarks invalid string parsing
using System; using System.Diagnostics; class Program { const int _max = 10000; static void Main() { // 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.
C# program that times int parse methods
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
Notes, algorithm. IntParseFast() converts a character like "1" to the integer 1. ASCII chars are stored in different positions than the equivalent numbers, but in the same order.
Info The earlier a digit occurs, the more times it must be multiplied by 10 to correctly parse the number.
Next As we read the string from the left to the right, the current digit is one-tenth of the previous one.
Multiply We can multiply the previous number by 10 to satisfy this condition. The 48 we use shifts ASCII digits to ints.
Notes, int. The word "int" in C# aliases the System.Int32 type. Code that uses "System.Int32.Parse" or "System.Int32.TryParse," it is equivalent to int.Parse and int.TryParse.
Notes, other types. Numbers can be smaller than an int (like a byte) or much larger (like a decimal). Each type has a useful Parse and TryParse method.
bool.Parse
decimal.Parse
double.Parse
long.Parse
A review. Programmers can write their own integer conversion routines. This is complicated. With Parse and TryParse, .NET helps solve the parsing problem.
Home
© 2007-2021 sam allen. see site info on the changelog