Cannot convert source type to compile error of target type
I have this simple class
public class Program
{
private static void Main(string[] args)
{
ClassB<ClassA> objA = new ClassB<ClassA>();
ClassB<ITestA<MyDTO>> objB = new ClassB<ClassA>();
}
}
public class ClassB<T>
{
///some code here
}
public interface ITestA<T>
{
///some code here
}
public class MyDTO
{
///some code here
}
public class ClassA : ITestA<MyDTO>
{
///some code
}
This line of code
ClassB<ITestA<MyDTO>> objB = new ClassB<ClassA>();
gives compilation error
Cannot implicitly convert type 'ClassB<ClassA>' to 'ClassB<ITestA<MyDTO>>
Since ClassA implements ITestA, I don't know why it will give a compilation error. Please help me understand what I am doing wrong.
Thanks, Esen
source to share
This is due to a rather complicated feature of generics called variance .
Classes are invariant, which means that if you declare ClassB<T>
, then on instantiation:
ClassB<T1> obj = new ClassB<T2>
Then T1
should be exactly the same class as T2
.
You can use interfaces to get around this, for example change your code to the following and it will compile:
...
public class Program
{
private static void Main(string[] args)
{
ClassB<ClassA> objA = new ClassB<ClassA>();
IClassB<ITestA<MyDTO>> objB = new ClassB<ClassA>();
}
}
public interface IClassB<out T> // <- note the out before T
{
//some code here
}
public class ClassB<T> : IClassB<T>
{
//some code here
}
...
In this case, it is IClassB
declared covariant, which means that it can handle the given derived class T
rather than itself T
. However, there are risks associated with using covariance (and contravariance), so generic classes are invariant by default.
source to share