0

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.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • 4
    Does this answer your question? [Convert char to int in C#](https://stackoverflow.com/questions/239103/convert-char-to-int-in-c-sharp) – devNull Jul 18 '20 at 15:55

3 Answers3

1

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';
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

If you want the literal character and not the ascii number of the character, use the ToString() method

var hola =  Convert.ToInt32(i.ToString());
Jawad
  • 11,028
  • 3
  • 24
  • 37
0

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.

Baturhan
  • 31
  • 4