Reputation: 13
when I display the 'i' variable, which would be a char value
{
class Program {
static void Main(string[] args) {
var max = 0;
var lista = new char[] {
'1',
'2',
'3',
'4'
};
foreach(char i in lista) {
Console.WriteLine(i);
/* var hola = Convert.ToInt32(i);
Console.WriteLine(hola);*/
}
}
}
}
I get this:
> 1 2 3 4
However, when converting 'i' into an int
var max = 0;
var lista = new char[] {
'1',
'2',
'3',
'4'
};
foreach(char i in lista) {
var hola = Convert.ToInt32(i);
Console.WriteLine(hola);
}
I get this:
49 50 51 52
Any idea what could be the problem? I'd like to obtain the same values, so I can evaluate them as integers and obtain the biggest of them, but I can't.
Upvotes: 0
Views: 374
Reputation: 31
WriteLine method internally converts the parameters string. Thus you can have the value you want. ToInt method return the ASCII value of that char. You have to convert your i value to string i.ToString()
or you can simply substract 48 from the converted value.
Upvotes: 0
Reputation: 11364
If you want the literal character and not the ascii number of the character, use the ToString()
method
var hola = Convert.ToInt32(i.ToString());
Upvotes: 0
Reputation: 312309
When you convert a char
to an int
, you get the ASCII value of that character. The neat thing with these values is that they are sequential, so if you subtract the value of '0'
(the 0 character), you can convert a character representing a digit to that digit:
var hola = i - '0';
Upvotes: 1