How do I convert a string to an integer in C#?
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;
}
int a = int.Parse(myString);
or better yet, look into int.TryParse(string)
int i;
string result = Something;
i = Convert.ToInt32(result);
class MyMath
{
public dynamic Sum(dynamic x, dynamic y)
{
return (x+y);
}
}
class Demo
{
static void Main(string[] args)
{
MyMath d = new MyMath();
Console.WriteLine(d.Sum(23.2, 32.2));
}
}
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;
}
You can use either,
int i = Convert.ToInt32(myString);
or
int i =int.Parse(myString);