Search code examples
c#arrays.netvalue-type

When trying to iterate over an integer array using 'foreach' it is possible to define the element's type as 'char'


I have encountered a very interesting thing in C#. For example, if you try to iterate over an array of integers using foreach statement, you basically can define item's type as char. For reference you can have a look at the code below:

Normally, you write this:

int[] arr = new int[] { 1, 2, 3, 4 };

foreach (int item in arr)
{
    Console.WriteLine(item);
}

But also, you can do this:

int[] arr = new int[] { 1, 2, 3, 4 };

foreach (char item in arr)
{
    Console.WriteLine(item);
}

The first code will write out all numbers in console. The second piece of code will print whitespaces. I want to know why it is possible to replace int with char inside foreach statement. And then, why whitespaces are getting printed?


Solution

  • The char with value 1 is different than the char with value '1' (which has the value 49)

    When displaying an int, you get the numerical representation (the number). When doing the same with a char, it's converted to its unicode representation (a character)

    More informations in documentation

    Here is the ascii table, for simplicity (the unicode one has way more characters)

    You can see the character 0 is null, the 1 is SOH, ... the character 49 is '1', the 50 is '2' and so on...

    enter image description here