Why Is It That Generics Constraint Can't Be Casted to Its Derived Type?

Posted by Ngu Soon Hui on Stack Overflow See other posts from Stack Overflow or by Ngu Soon Hui
Published on 2010-05-17T07:29:57Z Indexed on 2010/05/17 7:30 UTC
Read the original article Hit count: 187

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about c#

Related posts about generics