When we try to upcast from a Generic Type class to a formal implementation it gives a casting error.
In the code below you can see that I have a FormalClass that is an implementation of a GenericTypeClass. When I try to up cast from the GenericTypeClass to a FormalClass it it gives this error:
"[System.InvalidCastException: Unable to cast object of type 'GenericTypeClass`1[TestType]' to type 'FormalClass'.]"
I know that this will not work but if you need to do an up cast what is the best way to solve it? Automapper? Json serialization? Other?
Below is a dotnetfiddle ( https://dotnetfiddle.net/LLg0vp ) example:
using System;
public class Program
{
public static void Main()
{
var a = new GenericTypeClass<TestType>();
var b = a as FormalClass;
if (b == null)
Console.WriteLine("'a as Formal' Is NULL");
try
{
var c = (FormalClass)a;
}
catch (Exception ex)
{
Console.WriteLine("'(FormalClass)a' gives this error: " + ex.Message);
}
}
}
public class FormalClass : GenericTypeClass<TestType>
{
}
public class GenericTypeClass<T>
where T : class, IType
{
}
public class TestType : IType
{
}
public interface IType
{
}