0

I have defined a generic class MultiSlot<T>.

At some point I want to check that an object is of this type (i.e. of type MultiSlot), but not of a specific type T. What I want, basically, is all objects of MultiSlotl<T> to enter a certain if clause, regardless their specific T (given that they all belong to some subclass of T).

An indicative (but wrong!) syntax would be: if (obj is MultiSlot<>).

Is there a way to do that?

AakashM
  • 62,551
  • 17
  • 151
  • 186

3 Answers3

4

Have a look to Check if a class is derived from a generic class :

Short answer :

    public static bool IsSubclassOfRawGeneric(Type generic, Type toCheck)
    {
        while (toCheck != null && toCheck != typeof(object))
        {

            var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
            if (generic == cur)
                return true;
            toCheck = toCheck.BaseType;

        }
        return false;
    }
Community
  • 1
  • 1
Kek
  • 3,145
  • 2
  • 20
  • 26
  • please [cite](http://stackoverflow.com/a/457708/201088) the other answer when you copy/paste. – Eren Ersönmez Feb 14 '13 at 13:30
  • you are absolutely right @Eren Ersönmez... sorry, mistake corrected. I just didn't know how to find it again... and well, I should have truted StackOverflow search engine! My apologies – Kek Feb 14 '13 at 13:35
0

You can use the Type.GetGenericTypeDefinition() method, like this:

public bool IsMultiSlot(object entity)
{
  Type type = entity.GetType();
  if (!type.IsGenericType)
    return false;
  if (type.GetGenericTypeDefinition() == typeof(MultiSlot<>))
    return true;
  return false;
}

and you could use it like:

var listOfPotentialMultiSlots = ...;
var multiSlots = listOfPotentialMultiSlots.Where(e => e.IsMultiSlot());

Note that this will return false for an instance of a subclass (i.e. StringMultiSlot : MultiSlot<string>)

SWeko
  • 30,434
  • 10
  • 71
  • 106
0

A not so sophisticated approach:

var type = obj.GetType();
var isMultiSlot = type.IsGenericType && 
                  type.GetGenericTypeDefinition() == typeof (MultiSlot<>);

This won't work for types inherited from MultiSlot<T>, though.

Andre Loker
  • 8,368
  • 1
  • 23
  • 36