wonderful world
wonderful world

Reputation: 11599

Casting a generic class which is an object to it's type

This is a class hierarchy question related to generics. I have a mostly derived class MyClass3<T> which is derived from MyClass2<T>. The class MyClass2<T> has a property called MyProperty.

I have a method VerifyMyProperty which accepts an object of type MyClass3. Since it is generic, it can be MyClass3<A> or MyClass3<B> or MyClass3<C>.

My question is, how can I cast MyClass3 to MyClass2 to check the property MyProperty? Without generics, it would be easy as var myClass2 = anyofMyClass as MyClass2. With generics where the T can be A, B or C, how can I do the same casting?

public class MyClass3<T> : MyClass2<T>
{
....
}

public class MyClass2<T> : MyClass1
{
    T MyProperty { get; private set; }
}

public void VerifyMyProperty(object anyofMyClass)
{
    var myClass2 = anyofMyClass as MyClass2; // Finding the MyClass2. This line will return a compiler error.

    if (myClass2.MyProperty != null)
    {
       Console.Writeline("MyClass2.MYProperty is not null.");
    }
}

Upvotes: 0

Views: 73

Answers (1)

Martin Mulder
Martin Mulder

Reputation: 12954

First of all: In your example MyClass2 does not exists. Only MyClass<T> is a valid class.

So you might consider:

var myClass2 = anyofMyClass as MyClass2<T>;

In case anyOfMyClass must be able to contain a MyClass2 with another generic type, something goes wrong.

You might want to consider an implementation of a common and general interface with a property like:

interface IMyInterface
{
    object MyProperty { get; }
}

public class MyClass2<T> : MyClass1, IMyInterface
{
    T MyProperty { get; private set; }
    object IMyInterface.MyProperty { get { return MyProperty; }}
}

When you implement this interface explicitly (see: http://msdn.microsoft.com/en-us/library/aa664591(v=vs.71).aspx), you could solve your problem in the non-generic way:

var myClass2 = anyofMyClass as IMyInterface;
if (myClass2.MyProperty != null)
    ...

Upvotes: 2

Related Questions