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
  • 60,842
  • 17
  • 153
  • 183

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,075
  • 2
  • 19
  • 26
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
  • 29,624
  • 9
  • 71
  • 103
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,148
  • 1
  • 21
  • 36