views:

166

answers:

1

Why does this conversion not work?

public interface IMyInterface
{
}

public interface IMyInterface2 : IMyInterface
{
}

public class MyContainer<T> where T : IMyInterface
{
     public T MyImpl {get; private set;}
     public MyContainer()
     {
          MyImpl = Create<T>();
     }
     public static implicit T (MyContainer<T> myContainer)
     {
        return myContainer.MyImpl;
     }
}

When I use my class it causes a compile time error:

IMyInterface2 myImpl = new MyContainer<IMyInterface2>();

Cannot convert from MyContainer<IMyInterface2> to IMyInterface2...hmmmm

+5  A: 

You cannot define an implicit conversion to an interface. Therefore your generic implicit operation is not going to be valid for interfaces. See blackwasp.co.uk

You may not create operators that convert a class to a defined interface. If conversion to an interface is required, the class must implement the interface.

You may just have to end up writing the following, without implicit magic:

IMyInterface2 myImpl = new MyContainer<IMyInterface2>().MyImpl;
Greg