Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit Operator Conversion and Generics

Tags:

c#

generics

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

like image 779
Adam Driscoll Avatar asked Jan 23 '10 21:01

Adam Driscoll


People also ask

What is the concept of generics?

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.

What is an implicit operator?

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.

Do generics increase performance?

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.


1 Answers

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;
like image 65
Greg Avatar answered Oct 28 '22 03:10

Greg