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?
The
charwith value1is different than the char with value'1'(which has the value49)When displaying an
int, you get the numerical representation (the number). When doing the same with achar, 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
0isnull, the1isSOH, ... the character49is'1', the50is'2'and so on...