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


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


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.

vote vote


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


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


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#