views:

321

answers:

8

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

+3  A: 
int a = int.Parse(myString);

or better yet, look into int.TryParse(string)

Neil N
+3  A: 
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;
}
DanM
+2  A: 

If you are sure that you have "real" number in your string, or you are comfortable of any exception that might arise, use this.

string s="4";
int a=int.Parse(s);

For some more control over the process, use

string s="maybe 4";
int a;
if (int.TryParse(s, out a)) {
    // it's int;
}
else {
    // it's no int, and there's no exception;
}
Daniel Mošmondor
+1  A: 

Do you mean something like

var result = Int32.Parse(str);

?

Thomas Wanner
+18  A: 

If you're sure it'll parse correctly

int.Parse(string)

If you're not

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

Caution! In this case, 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.

Brandon
Very Good Answer
@sslaitha, thanks. If it answered your question sufficiently, please remember to mark it as the answer.
Brandon
Just note that if you have int i = 10; and use int.TryParse("asdf", out i); that i will contain 0 not 10!!! This is because TryParse uses an out variable, not a ref.
Chad
+1  A: 
int i;
string whatever;

//Best since no exception raised
int.TryParse(whatever, out i);

//Better use try catch on this one
i = Convert.ToInt32(whatever);
madatanic
+3  A: 
string varString = "15";
int i = int.Parse(varString);

or

int varI;
string varString = "15";
int.TryParse(varString, out varI);

int.TryParse is safer since if you put something else in varString (for example "fsfdsfs") you would get an exception. By using int.TryParse when string can't be converted into int it will return 0.

MadBoy
A: 
int i;

string result = Something;

i = Convert.ToInt32(result);
deepu