With reference to InvalidCastException on Generics, I have adapted the given answer for my own application. As an example:
public interface IData
{
string getValue();
}
public interface IController<in T> where T : IData
{
string formString(T data);
}
public class DataImplA : IData
{
public string getValue()
{
return "DataImplA";
}
}
public class ControllerImplA : IController<DataImplA>
{
public string formString(DataImplA data)
{
return "ControllerImplA, " + data.getvalue();
}
}
public class Program
{
private static IController<IData> controller;
public static void main(string[] args)
{
// Line with error
Program.controller = (IController<IData>)new ControllerImplA();
Console.WriteLine(Program.controller.formString(new DataImplA()));
}
}
During runtime, the indicated line will trigger
InvalidCastException: Unable to cast object of type 'ControllerImplA' to type 'IController`1[IData].
I tried changing to Program.controller = (IController<IData>)new ControllerImplA<DataImplA>(); but this results in the compilation error The non-generic type 'ControllerImplA' cannot be used with type arguments
I then tried changing the class definition to public class ControllerImplA<DataImplA> : IController<DataImplA> but then the new compilation error is:
The type 'DataImplA' cannot be used as type parameter 'T' in the generic type or method 'IController T'. There is no boxing conversion or type parameter conversion from 'DataImplA' to 'IData'.
I don't want to use public class ControllerImplA<T> : IController<T> because the constraint is that ControllerImplA can only use DataImplA, ControllerImplB can only use DataImplB and so on so forth.
How should I correct my original code?