Dofactory.com
Dofactory.com

How can I convert a string to an int in C#.

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");


Jack Poorte
Jack Poorte
Last updated on Sep 30, 2023



Stay Inspired!
Join other developers and designers who have already signed up for our mailing list.
Terms     Privacy     Cookies       Do Not Sell       Licensing      
Made with    in Austin, Texas.  - vsn 44.0.0
© Data & Object Factory, LLC.