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
Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.
According to MSDN, an implicit keyword is used to declare an implicit user-defined type conversion operator. In other words, this gives the power to your C# class, which can accepts any reasonably convertible data type without type casting.
With using generics, your code will become reusable, type safe (and strongly-typed) and will have a better performance at run-time since, when used properly, there will be zero cost for type casting or boxing/unboxing which in result will not introduce type conversion errors at runtime.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With