rookie
rookie

Reputation: 2923

Recasting where two types share a common base type

We have some code like the following:

    class Base
    {
        public string Name;
    }

    class DeeperBase : Base
    {
    }

    class A : Base
    {
        public A()
        {
            Name = "A";
        }
    }

    class B : DeeperBase
    {
        public B()
        {
            Name = "B";
        }
    }

    static T Recast<T>(Base original) where T : Base, new()
    {
        if (!original.GetType().IsAssignableFrom(typeof(T)))
            throw new InvalidCastException();
        return new T();
    }

It looks like Recast is trying to check if the two types are compatible before returning a new T. The method fails, however, for the following code.

    public static void Main(string[] args)
    {
        var a = new A();
        var b = Recast<B>(a); // exception
    }

What's the proper way to check that T and original share the greatest common base type (in this case, Base)?

Upvotes: 0

Views: 87

Answers (1)

Patrick Hofman
Patrick Hofman

Reputation: 157048

You are trying to cast an instance A to B, which it can't, since they are not the same type, nor does A derive from B.

There is no way to cast A to B. You could do a Recast<Base>(a), but that doesn't make sense. Note that you are not actually changing the type in any way, you are just returning a new instance of B, or throw an exception.

Upvotes: 2

Related Questions