0

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?

Rand Random
  • 7,300
  • 10
  • 40
  • 88
Niyazi Babayev
  • 120
  • 2
  • 9
  • 2
    https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/iteration-statements#type-of-an-iteration-variable – bigcrazyal Jul 06 '23 at 19:42
  • 1
    1. It's converted to a `char` because you told it to, and an `int` can be cast to a `char` so there isn't an exception thrown. 2. It's trying to print the character that corresponds to character code of 1, 2, etc. – bigcrazyal Jul 06 '23 at 19:45
  • 1
    if it is castable you can declare it as the type and (char)1 isn‘t the number 1 - https://dotnetfiddle.net/zlHq3X – Rand Random Jul 06 '23 at 19:47
  • 1
    `foreach` is translated somewhat, see https://stackoverflow.com/q/3679805/1462295 . The collection (`arr` in your case) is enumerated, and the `item` cast to the loop type (`char` in your case). – BurnsBA Jul 06 '23 at 20:17
  • 1
    Try making one of those integers be 256 or greater. A `char` is a one-byte integral type. Exceed 255 and you overflow – Flydog57 Jul 06 '23 at 21:54

2 Answers2

2

When you use Console.WriteLine(item) inside the foreach loop with char as the iteration variable, it attempts to display the Unicode character corresponding to each int value. Since these characters are control characters, they are not visible in the console output, and you see whitespace instead.

Alex Gordon
  • 57,446
  • 287
  • 670
  • 1,062
2

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

Cid
  • 14,968
  • 4
  • 30
  • 45
  • I supposed that it can be because of the fact that it tries to lookup for the value in the ASCII table. Now it is all clear. Thank you! – Niyazi Babayev Jul 06 '23 at 21:23