How do I convert a string to an integer in C#?
You convert a string to a number by calling the Parse or TryParse method found on numeric types ( int , long , double , and so on), or by using methods in the System. Convert class. It's slightly more efficient and straightforward to call a TryParse method (for example, int.
The atoi() function converts a character string to an integer value. The input string is a sequence of characters that can be interpreted as a numeric value of the specified return type. The function stops reading the input string at the first character that it cannot recognize as part of a number.
We can convert char to int by negating '0' (zero) character. char datatype is represented as ascii values in c programming. Ascii values are integer values if we negate the '0' character then we get the ascii of that integer digit.
int myInt = System.Convert.ToInt32(myString);
As several others have mentioned, you can also use int.Parse()
and int.TryParse()
.
If you're certain that the string
will always be an int
:
int myInt = int.Parse(myString);
If you'd like to check whether string
is really an int
first:
int myInt; bool isValid = int.TryParse(myString, out myInt); // the out keyword allows the method to essentially "return" a second value if (isValid) { int plusOne = myInt + 1; }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With