How to convert string to integer in C#

user282078 picture user282078 · Feb 26, 2010 · Viewed 178.2k times · Source

How do I convert a string to an integer in C#?

Answer

Brandon picture Brandon · Feb 26, 2010

If you're sure it'll parse correctly, use

int.Parse(string)

If you're not, use

int i;
bool success = int.TryParse(string, out i);

Caution! In the case below, i will equal 0, not 10 after the TryParse.

int i = 10;
bool failure = int.TryParse("asdf", out i);

This is because TryParse uses an out parameter, not a ref parameter.