Friday, 20 July 2007

Dynamic nature of C# I bet you don't know :)

Yesterday I read a blog post that meant to discuss possible naming conventions for LINQ but it turned out that the most interesting part of it was something completely different. Namely, Krzysztof Cwalina wrote that we don't have to implement IEnumerable and IEnumerator to be able to iterate through an object(collection) using foreach statement. It's enough that a class exposes GetEnumerator() method. It doesn't have to implement IEnumerable interface. At the beginning I thought that it's just another example of syntactic sugar and that the C# compiler generates implicit IEnumerable declaration on our behalf. But then I opened ildasm.exe and saw that that's not the case. IEnumerable wasn't there. That's it. Have a look at the code snippet and screen shot below to check it out.
The bottom line is that I learn every day and .NET doesn't stop surprising me which is fun :).
EDIT: I've modified the image because it looked horrible.

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
class Program
{
    static void Main(string[] args)
    {
        FakeEnumerableClass enumerable = new FakeEnumerableClass();

        foreach (object o in enumerable)
        {

            //works perfectly fine :)
        }
    }
}
class FakeEnumerableClass
{
    public FakeEnumerator GetEnumerator()
    {
        return new FakeEnumerator();
    }
}
public class FakeEnumerator
{
    public bool MoveNext()
    {
        return false;
    }

    public object Current
    {
        get
        {
            return null;
        }
    }
}
class RealEnumberableClass : IEnumerable
{
    public IEnumerator GetEnumerator()
    {
        throw new Exception("The method or operation is not implemented.");
    }
}


 

No comments:

Post a Comment