C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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);
}
}
Output
500
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);
}
}
Output
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, ...
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.
OutTrue, FalseNull: 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);
}
}
Output
0
10000
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);
}
}
Output
0
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);
}
}
}
Output
346
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);
}
}
Output
500
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);
}
}
}
Output
1/22/2017 12:00:00 AM
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: 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"));
}
}
Output
24839.68 ns int.Parse
54.01 ns int.TryParse
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 the .NET Framework. This version supports more number formats.
Result: The custom method IntParseFast is much faster for parsing a simple 6-character integer.
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"));
Console.Read();
}
}
Output
123456
123456
4.53 ns: IntParseFast
116.67 ns: int.Parse
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 simply shifts ASCII digits to ints.