I’m targeting version 4.0 of the .Net framework. I wrote the following simple code:
public class A
{
public A()
{
}
}
public class B
{
public B()
{
}
public static implicit operator A(B b)
{
return new A();
}
}
Then I created a generic list:
var mylist = typeof(List<>).MakeGenericType(typeof(A)).GetConstructor(Type.EmptyTypes).Invoke(new object[]{});
When I want add a new instance of B the following code works:
((IList<A>)mylist).Add(new B());
However if I run the below code the following exception is thrown:
The value "B" is not of type "A" and cannot be used in this generic collection.
Parameter name: value
((IList)mylist).Add(new B());
The implicit conversion happens only in the first
Addas you are adding an object of typeBto aIList<A>. In the second case, you are adding it to the non-genericIList, which is a collection of objects and the implicit conversion doesn’t take place and bombs when the object is actually added to yourList<A>Even this fails:
You can do this, however: