I want to be able to declare a generic instance that takes a base class as a type parameter and then later assign it to a generic that takes the subclass as the parameter. I have been able to do similar things in Java, but I'm stuck here in C#.
The best use case for a problem like this would be to map different interactions to two class types, which I have done in this code snippet. I tried to declare a Base class and classes A and B that derive from it. Then I want to map a function which takes the two classes as parameters.
class Program
{
public class Base {}
public class A : Base {}
public class B : Base {}
public class TypePair
{
private Type left;
private Type right;
public TypePair(Type left, Type right)
{
this.left = left;
this.right = right;
}
}
public static Dictionary<TypePair, Func<Base, Base, bool>> typeMap = new Dictionary<TypePair, Func<Base, Base, bool>>();
public static bool doStuffWithAandB(A a, B b)
{
Console.WriteLine("Did stuff with a and b!");
return true;
}
public static void Main(string[] args)
{
var typePair = new TypePair(typeof(A), typeof(B));
typeMap.Add(typePair, doStuffWithAandB); // <- Compiler error :(
typeMap[typePair](new A(), new B());
}
}
The compiler expects a generic (Func) like doStuffWithAandB(Base a, Base b) and not doStuffWithAandB(A a, B b). If C# does not allow such a functionality. Why is that and are the better solutions to problems like these?