Given the following code:
static void Main() {
string[] myArray = {"One", "Two", "Three"};
PrintArray(myArray);
}
static void PrintArray(System.Array array1) {
foreach (string s in array1)
Console.WriteLine(s);
}
I'm surprised that I could compile those lines without error, since in PrintArray
the compiler cannot know what kind of array array1 is (in this case it's System.string[]
). If I change the foreach line as such: foreach (int s in array1)
, the code will still compile, but will generate an runtime invalid casting exception.
Shouldn't the compile in this case assure only Object could be used in the foreach statement?
By specifying the type of the loop variable you are explicitly unboxing/casting each element in your array as that type.
In the case of a string, it is a cast from object to string.
If your array would be an int array you would be doing an unboxing operation instead of a cast.