Implicit statement using interfaces

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; // doesn't work 

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.

+44
compiler-construction generics casting c # implicit-conversion
Sep 27 '08 at 12:02
source share
1 answer

The reason you cannot do this is because it is specifically prohibited in the C # language specification:

A class or structure is allowed to declare a conversion from a source of type S to a target type of T, provided that all of the following statements:

  • ...
  • Neither S nor T are object or interface.

and

Custom conversions are not allowed to convert from or to an interface-type. In particular, this restriction ensures that no user conversions occur when converting to an interface type, and that switching to an interface type is successful only if the actually converted object implements the specified Interface type.

Source

+45
Sep 27 '08 at 12:37
source share



All Articles