Class A { }
Class B : A { }
B ItemB = new B();
A ItemA = (A)B;
Console.WriteLine(ItemA.GetType().FullName);
Is it possible to do something like a
I've recently run into this migrating an old project to Entity Framework. As it was mentioned, if you have a derived type from an entity, you can't store it, only the base type. The solution was an extension method with reflection.
public static T ForceType(this object o)
{
T res;
res = Activator.CreateInstance();
Type x = o.GetType();
Type y = res.GetType();
foreach (var destinationProp in y.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
{
var sourceProp = x.GetProperty(destinationProp.Name);
if (sourceProp != null)
{
destinationProp.SetValue(res, sourceProp.GetValue(o));
}
}
return res;
}
It's not too neat, so use this if you really have no other option.