Here is a little puzzle for C# developers reading my blog. What is the error in the program below?

   using System.Collections.Generic;
   class Program
   {
       public static void Main()
       {
           int[] arr = new int[10];
           IEnumerator<int> e = arr.GetEnumerator();
       }
   }

If you don’t see it, don’t worry.  I was surprised by this C# behavior as well. Just come back in a couple days to see the solution. Or try to compile the program in Visual Studio. :-)

PS.: The cause for the low cadency of posts on my blog is a side project (an online game written in Silverlight) that has been draining away my extra time over the last few months. Expect an announcement in two to three weeks, once it’s ready for launch.


Tags:

4 Comments to “Puzzling over arrays and enumerators in C#”

  1. Peter says:

    You get this error:

    Cannot implicitly convert type ‘System.Collections.IEnumerator’ to ‘System.Collections.Generic.IEnumerator<T>’.

    To make the code compilable you need to create a cast:

    IEnumerator<T> e = (IEnumerator<T>) arr.GetEnumerator();

    or safe cast:

    IEnumerator<T> e = arr.GetEnumerator() as IEnumerator<T>

  2. Paul says:

    A simple cast:

    IEnumerator e = (IEnumerator)arr.GetEnumerator();
    or
    IEnumerator e = arr.GetEnumerator() as IEnumerator;

    won’t have the desired effect. The former will throw a cast exception and the latter will result in e being null.

    It should first be converted to Enumerable and then get the Enumerator:

    IEnumerator e = arr.AsEnumerable().GetEnumerator();

    And now I’m hoping that this is wrong and there’s an easier way, because that’s damned ugly when you think about it …

  3. Paul says:

    <grumble> cut-and-paste bites me again, sorry for the duplicate

    A simple cast:

    IEnumerator<int> e = (IEnumerator<int>)arr.GetEnumerator();
    or
    IEnumerator<int> e = arr.GetEnumerator() as IEnumerator<int>;

    won’t have the desired effect. The former will throw a cast exception and the latter will result in e being null.

    It should first be converted to Enumerable and then get the Enumerator:

    IEnumerator<int> e = arr.AsEnumerable<int>().GetEnumerator();

    And now I’m hoping that this is wrong and there’s an easier way, because that’s damned ugly when you think about it …

  4. @Paul: Yeah, the comment system is very frustrating. I need to find a good comment plugin.

    You make an interesting point. I did not try casting the non-genetic enumerator to a generic one, but I am actually mildly surprised that you will get a cast exception.

    Igor
    PS.: A follow-up post is coming (haven’t gotten around to it yet).

Leave a Reply

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>