Поделиться через


C# quiz answer - yes it compiles, and here's why

Got a few good comments to the quiz post, but nobody that commented got it right.  I went ahead and sent the quiz on an internal C# mailing list, and to nobody's surprise, multiple people got it right :)

The key bit of information is that the one thing you can add to the Class2 declaration that would keep the program from compiling is "sealed".

The core question was basically - how does foreach (Class2 c in ienum1) make sense if ienum1 is declared as IEnumerable<Inter1> and Class2 doesn't implement Inter1?  And the answer is that the actual instances in ienum1 can *both* cast to Class2 fine (required for the foreach) *and* implement Inter1 fine (to be in the ienum1) because Class2 isn't sealed - all we need is a class that subclasses Class2 and implements Inter1 as well.

Here's the modified code that shows this in action:

 using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        IEnumerable<Inter1> ienum1 = new Class3[] { new Class3() }; 
        foreach (Class2 c in ienum1)
        {
            Console.WriteLine(c);
        }
    }
}

public interface Inter1 { int MyProperty { get; } }
public class Class1 : Inter1 { public int MyProperty { get { return 0; } } }
public class Class2 { }
public class Class3 : Class2,  Inter1 { public int MyProperty { get { return 0; } } }

Comments