Why Is It That Generics Constraint Can't Be Casted to Its Derived Type?
- by Ngu Soon Hui
It is quite puzzling to find out that Generics Constraint Can't Be Casted to Its Derived Type.
Let's say I have the following code:
public abstract class BaseClass
{
public int Version
{
get
{
return 1;
}
}
public string FixString
{
get;
set;
}
public BaseClass()
{
FixString = "hello";
}
public virtual int GetBaseVersion()
{
return Version;
}
}
public class DeriveClass: BaseClass
{
public new int Version
{
get
{
return 2;
}
}
}
And guess what, this method will return a compilation error:
public void FreeConversion<T>(T baseClass)
{
var derivedMe = (DeriveClass)baseClass;
}
I would have to cast the baseClass to object first before I can cast it to DerivedClass.
Seems to me pretty ugly. Why this is so?