Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string to integer in C#

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

like image 621
user282078 Avatar asked Feb 26 '10 19:02

user282078


People also ask

How can a string be converted to a number?

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.

What is atoi () in C?

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.

Can we convert a character to integer in C?

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.


2 Answers

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; } 
like image 39
devuxer Avatar answered Oct 09 '22 18:10

devuxer


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.

like image 103
Brandon Avatar answered Oct 09 '22 16:10

Brandon