Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What difference between the element type and the loop variable type inside foreach loop?

Tags:

c#

foreach

C# spec says that foreach statement will be expanded to:

{
    E e = ((C)(x)).GetEnumerator();
    try {
        while (e.MoveNext()) {
            V v = (V)(T)e.Current; // <-- double cast. For what?
            embedded-statement
        }
    }
    finally {
        … // Dispose e
    }
}

Why the following will be incorrect?

V v = (V)e.Current;
like image 608
rzaitov Avatar asked Feb 07 '26 14:02

rzaitov


1 Answers

To help answer the question lets get some contenxt, the prior lines of the specification say:


The above steps, if successful, unambiguously produce a collection type C, enumerator type E and element type T. A foreach statement of the form

foreach (V v in x) embedded-statement

is then expanded to

{
    E e = ((C)(x)).GetEnumerator();
    try {
        while (e.MoveNext()) {
            V v = (V)(T)e.Current; // <-- double cast. For what?
            embedded-statement
        }
    }
    finally {
        … // Dispose e
    }
}

Prior to this is a whole section about how to determine what 'C', 'E', and 'T' are.

I suggest anyone who is interested read it, BUT what is important the type of V can be different than than the type returned by the enumeration on x which has to be able to cast to type T (but can still be a different type) and T has to be able to cast to V.

So this:

 V v = (V)(T)e.Current;

Does that... first it take the enumerations current value and casts it to the type T and then casts that to the type V.

For example consider the following code

void Main()
{
  double [] values = { 1.1,2.2,3.3,4.4,5.5 };

  foreach(int number in values)
  {
    Console.WriteLine(number);
  }     

}

In this case T is double and V is int.

like image 180
Hogan Avatar answered Feb 09 '26 07:02

Hogan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!