Check general type

I want to check if a shared variable is of a specific type, but does not want to check the common part.

Let's say I have a variable List<int>and one more of List<double>. I just want to check if it is of typeList<>

if(variable is List) {}

And not

if (variable is List<int> || variable is List<double>) {}

Is it possible?

thanks

+3
source share
3 answers
variable.GetType().IsGenericType && 
            variable.GetType().GetGenericTypeDefinition() == typeof(List<>)

Of course, this only works if the variable is of type List<T>and is not a derived class. If you want to check whether this is List<T>or inherited from it, you must go through the inheritance hierarchy and check the above statement for each base class:

static bool IsList(object obj)
{
    Type t = obj.GetType();
    do {
        if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(List<>))
            return true;
        t = t.BaseType;
    } while (t != null);
    return false;
}
+9
source

You can check the exact type using reflection:

    object list = new List<int>();

    Type type = list.GetType();
    if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
    {
        Console.WriteLine("is a List-of-" + type.GetGenericArguments()[0].Name);
    }

IList<T> - , List<T>:

    foreach (Type interfaceType in type.GetInterfaces())
    {
        if (interfaceType.IsGenericType
            && interfaceType.GetGenericTypeDefinition()
            == typeof(IList<>))
        {
            Console.WriteLine("Is an IList-of-" +
                interfaceType.GetGenericArguments()[0].Name);
        }
    }
+6
Type t = variable.GetType();
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(List<>))
{
    // do something
}
+5

Source: https://habr.com/ru/post/1715158/


All Articles