In C#, you can convert a string representation of a number to an integer in 3 different ways:
Parse()
, TryParse()
, and the Convert
class.
Example: Convert string to int using Parse()
.
short value1 = short.Parse("100");
int value2 = int.Parse("100");
long value3 = long.Parse("100");
// Alternatively
short value4 = Int16.Parse("100");
int value5 = Int32.Parse("100");
long value6 = Int64.Parse("100");
Example: Convert string to int using TryParse()
.
string str = "12345";
if (int.TryParse(str, int out number)
Console.WriteLine(number);
else
Console.WriteLine("Unable to parse string.");
Example: Convert string to int using the Convert
class.
short value1 = Convert.ToInt16("100");
int value2 = Convert.ToInt32("100");
long value3 = Convert.ToInt64("100");