Implicit casting IEnumerable to generic type
I ran into an interesting case when playing with implicit key presses and IEnumerable - see the last line of the attached code - it won't compile.
public class Outer<T>
{
private T field;
public Outer(T it)
{
field = it;
}
public static implicit operator Outer<T> (T source)
{
return new Outer<T>(source);
}
}
void Main()
{
Outer<string> intsample = "aa";
Outer<IList<object>> listsample = new List<object>();
//The line below fails with:
//CS0266 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<object>'
//to 'UserQuery.Outer<System.Collections.Generic.IEnumerable<object>>'.
//An explicit conversion exists (are you missing a cast?)
Outer<IEnumerable<object>> enumerablesample = Enumerable.Empty<object>();
}
I have a very strong gut feeling that it is uplifted IEnumerable
by being covariant, but can anyone explain which is more formal?
+3
source to share
1 answer
A class or structure is allowed to declare a conversion from source type S to target type T if everything is true:
- S and T are different types.
- Either S or T is the type of class or structure in which the operator is declared.
- Neither S nor T is an object or type interface . T is not the base class of S, and S is not the base class of T.
Simple fix:
Enumerable.Empty<object>();
in
new List<object>();
What works with is List
not an interface (thanks @PatrickHofman!).
+2
source to share