Content

Not quite a Yegge long.

Abusing collection initializers in C#3

Wednesday 31 March 2010 - Filed under Uncategorized

Until today, I had made good use of the C#3 collection initializer syntax, but hadn’t thought to write a class that could accept it. Here’s the requirements:

  1. You must implement System.Collections.IEnumerable. The implementation is never actually used.
  2. For each set of types you want to use as an initializer, there must be a method Add() which can accept those types.
  3. The empty initializer {} is explicitly banned, even if there is an unambiguous overload of Add() for it.

This example works. It’s not sane, but that’s not the point:

using System.Collections;
class Blah : IEnumerable
{
    public void Add(int a, int b, int c, int d) { }
    public void Add(float e, float f) { }
    public void Add(params string[] gs) { }

    static void Foo()
    {
        var blah = new Blah
        {
            { 2f, 6.5f },
            { 1,2,5,42 },
            { "This", "is", "not", "really", "sane…" },
        };
    }

    public IEnumerator GetEnumerator() { return null; }
}

2010-03-31  »  admin

Share your thoughts

Re: Abusing collection initializers in C#3







Tags you can use (optional):
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>