Convert char to int in C#
This will convert it to an int:
char foo = '2';
int bar = foo - '0';
This works because each character is internally represented by a number. The characters '0' to '9' are represented by consecutive numbers, so finding the difference between the characters '0' and '2' results in the number 2.
Interesting answers but the docs say differently:
Use the
GetNumericValue
methods to convert aChar
object that represents a number to a numeric value type. UseParse
andTryParse
to convert a character in a string into aChar
object. UseToString
to convert aChar
object to aString
object.
http://msdn.microsoft.com/en-us/library/system.char.aspx
Has anyone considered using int.Parse()
and int.TryParse()
like this
int bar = int.Parse(foo.ToString());
Even better like this
int bar;
if (!int.TryParse(foo.ToString(), out bar))
{
//Do something to correct the problem
}
It's a lot safer and less error prone
char c = '1';
int i = (int)(c - '0');
and you can create a static method out of it:
static int ToInt(this char c)
{
return (int)(c - '0');
}