Sunday, March 4, 2012

Oh C#, why must you make life so difficult?

Ran into a problem with C#'s implicit conversions, which don't seem to support generic types:

class Foo<T>
{
    public T Value { get; set; }
    public static implicit operator Foo<T>(T value)
    {
        return new Foo<T> { Value = value };
    }
}
static class Program
{
    static void Main(string[] args)
    {
        // this is fine:
        Foo<IEnumerable<int>> x = new int[0];

        // this is not fine:
        Foo<IEnumerable<int>> y = Enumerable.Empty<int>();
        //Error 2: Cannot implicitly convert type 'IEnumerable<int>'
        //to 'Foo<IEnumerable<int>>'. An explicit conversion
        //exists (are you missing a cast?
    }
}

So basically, you can't implicitly convert nested generic types, but implicit array conversions work just fine.

No comments: