From C# 4.0 Spec section 6.1.6:
The implicit reference conversions are:
[…]
From any reference-type to an interface or delegate type T if it has
an implicit identity or reference conversion to an interface or
delegate type T0 and T0 is varience-convertible (13.1.3.2) to T.
Vladimir Reshetnikov tells us that there is an implicit reference conversion from List<string> to IEnumerable<object>. But, how can I apply this to a user defined type (is it even possible)?
I tried an implicit operator, custom derived types and a few varitions there-of…but I cannot reproduce the scenerio. I have:
class Program
{
static void Main(string[] args)
{
IEnumerable<object> specialClassConversion = new List<string>();
IEnumerable<A> userdefinedTypeConversion = new List<B>();
A implicitConversion = new B();//varience-convertible
IC<A> explicitConversion = (IC<A>)new D<B>();//OK, varience-convertible
IC<A> implicitConversion2 = new D<B>();//does not compile
}
}
class A { }
class B : A { }
interface IC<T> { }
class D<T>
{
//public static implicit operator IC(D<T> m)//Error: user-defined conversions to or from an interface are not allowed
//{
// return null;
//}
}
If you want a user-defined class or struct to be implicitly convertible to an interface, let your class/struct implement that interface.
(Edit)
And if you want
IC<B>to be implicitly convertible toIC<A>, make theIC<T>interface covariant inTby specifying theoutkeyword,interface IC<out T> { }. The quote from the spec you gave tells that the “composition” of these two implicit conversion is also an implicit conversion.Source:
(End edit)
Regarding the
List<string>class, it implementsIEnumerable<string>which in turn is convertible (implicitly) toIEnumerable<object>becauseIEnumerable<out T>is covariant (out) inT.(One reason why they didn’t allow you to make a
public static implicit operatorwhich converts to/from the interface, is that somone could write a derived class which inherited from your class and implemented the interface. That would give a “natural” conversion between their class and the interface, but thepublic static implicit operatorwould also apply, leading to two conversions (one “natural” and one “user-defined”) between the types, which would be confusing and ambiguous.)