Where T: IEnumerable <T> method restriction
From time to time I try to torture the C # compiler. Today I came up with this:
static void CallFirst<T>(T a) where T : IEnumerable<T>
{
a.First().ToString();
}
It was a simple mistake, because I wanted to create a general method that takes as a parameter a 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 a method CallFirst()? Each time a collection is transferred, collection collection is expected.
If this is not the case, should this not be taken as a compile-time error?
+4
2 answers
Of course:
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);
+2