tags:

views:

17965

answers:

5
+9  Q: 

C# char to int

So I have a char in c#:

char foo = '2';

Now I want to get the 2 into an int. I find that Convert.ToInt32 returns the actual decimal value of the char and not the number 2. The following will work:

int bar = Convert.ToInt32(new string(foo, 1));

int.parse only works on strings as well.

Is there no native function in C# to go from a char to int without making it a string? I know this is trivial but it just seems odd that there's nothing native to directly make the conversion.

+4  A: 

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.

yjerem
More importantly, why was it down-voted?
Erik Forbes
It works because 0 is 48.
sontek
Downvoting because I can only see mechanism, not intent.
Jay Bazuzi
It assumes a certain character set.
EricSchaefer
No it doesn't, as long as the digits are in order (which compilers require of the charset) it will work, no matter what value they start on.
yjerem
This is fine, except that you still need to do bounds-checking first, and at that point I'm not sure whether int.parse(foo.ToString()) is faster.
Matthew Flaschen
+8  A: 
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');
}
sontek
+17  A: 

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

faulty
Absolutely the right approach. Choose the first one if you want non-int inputs to throw, the second if you want to do something else.
Jay Bazuzi
This is a good approach for a generic conversion method. As an aside, its another example of how .NET promotes bloatware. (I mean go on and unit-test TryParse() and ToString() - you can't, not practically).
logout
A: 

gracias.. me ayudaron mucho. hace horas que estoy con eso

+9  A: 

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

Chad Grant
ahh! so there is something native! Odd that it returns a double. I like this answer better. Thanks for pointing it out.
KeithA