I have a generic class that I am trying to implement with an implicit type. Although it works mainly, it will not work for casting an interface. After further investigation, I found that there is a compiler error: "User-defined conversion from interface" that applies. Although I understand that this must be respected in some cases, what I'm trying to do seems to be a legitimate case.
Here is an example:
public class Foo<T> where T : IBar { private readonly T instance; public Foo(T instance) { this.instance = instance; } public T Instance { get { return instance; } } public static implicit operator Foo<T>(T instance) { return new Foo<T>(instance); } }
Code for use:
var concreteReferenceToBar = new ConcreteBar(); IBar intefaceReferenceToBar = concreteReferenceToBar; Foo<ConcreteBar> concreteFooFromConcreteBar = concreteReferenceToBar; Foo<IBar> fooFromConcreteBar = concreteReferenceToBar; Foo<IBar> fooFromInterfaceBar = intefaceReferenceToBar;
Does anyone know a workaround or can someone explain in a satisfactory way why I cannot use interfaceReferenceToBar implicitly for Foo<IBar> , since in my case it is not converted, but only contained inside Foo
EDIT: It seems that covariance may offer salvation. Let hope that the C # 4.0 specification allows for implicit casting of interface types using covariance.
compiler-construction generics casting c # implicit-conversion
Michael Meadows Sep 27 '08 at 12:02 2008-09-27 12:02
source share