John Landheer
John Landheer

Reputation: 4019

Determine which genric type object is derived from

I have the following classes:

public abstract class CommandBase
{
... Stuff
}

public abstract class Command<TArgumentType>  
           : CommandBase where TArgumentType : class
{
    protected TArgumentType Argument { get; private set; }

    protected Command(TArgumentType argument)
    {
        Argument = argument;
    }
}

public abstract class Command<TArgumentType, TReturnType>  
           : Command<TArgumentType> where TArgumentType : class
{
    public TReturnType ReturnValue{ get; protected set; }

    protected Command(TArgumentType argument) : base(argument)
    {
    }
}

How do I determine if an object is of type Command<TArgumentType> or Command<TArgumentType, TReturnType>? I don't know what specific types TArgumentType or TReturnType are. Or should I just do a simple try/catch around:

var returnValue = object.ReturnValue;

Upvotes: 2

Views: 136

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500525

If you don't know the type at compile-time, then foo.ReturnValue won't even compile, unless it's of type dynamic.

You can use something like this:

static bool ContainsGenericClassInHierarchy(object value,
                                            Type genericTypeDefinition)
{
    Type t = value.GetType();
    while (t != null)
    {
        if (t.IsGenericType
            && t.GetGenericTypeDefinition() == genericTypeDefinition)
        {
            return true;
        }
        t = t.BaseType;
    }
    return false;
}

Call it like this:

// Single type parameter
bool x = ContainsGenericClassInHierarchy(foo, typeof(Command<>));
// Two type parameters
bool y = ContainsGenericClassInHierarchy(foo, typeof(Command<,>));

Note that this won't work for finding implemented interfaces, which is somewhat trickier.

Upvotes: 4

Related Questions