Convert char to int in C#

ID : 20336

viewed : 45

Tags : c#charintc#

Top 5 Answer for Convert char to int in C#

vote vote

97

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.

vote vote

82

Interesting answers but the docs say differently:

Use the GetNumericValue methods to convert a Char object that represents a number to a numeric value type. Use Parse and TryParse to convert a character in a string into a Char object. Use ToString to convert a Char object to a String object.

http://msdn.microsoft.com/en-us/library/system.char.aspx

vote vote

80

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

vote vote

61

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'); } 
vote vote

59

Try This

char x = '9'; // '9' = ASCII 57  int b = x - '0'; //That is '9' - '0' = 57 - 48 = 9 

Top 3 video Explaining Convert char to int in C#

Related QUESTION?