Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

where T : IEnumerable<T> method constraint

From time to time I'm trying to torment the C# compiler. Today I came up with this:

static void CallFirst<T>(T a) where T : IEnumerable<T>
{
    a.First().ToString();
}

It was simple mistake, as I wanted to create the generic method that takes collection as parameter, which of course should look like this:

static void CallFirst2<T>(IEnumerable<T> a)
{
    a.First().ToString();
}

Anyway, is it even possible to call the CallFirst() method? Every time the collection is passed, the collection of collections is expected.

If it is not, shouldn't it be taken as compile time error?

like image 281
Bart Juriewicz Avatar asked Nov 01 '22 14:11

Bart Juriewicz


1 Answers

Sure:

class Test : IEnumerable<Test>
{
    IEnumerator<Test> IEnumerable<Test>.GetEnumerator()
    {
        throw new NotImplementedException();
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        throw new NotImplementedException();
    }
}

    ...

var test = new Test();
CallFirst(test);
like image 187
Henrik Avatar answered Nov 09 '22 21:11

Henrik