Is it possible to type check using `is` without knowing the generic used in C#?

Advertisements

In C#, is it possible to check if a variable is of a specific type that uses a generic, without knowing what that generic is? For example, the code

using System;
using System.Collections.Generic;

public static class Program {
    public static void Main(string[] args) {
        List<string> list = new List<string>();

        if (list is List<object>)
            Console.WriteLine("Success");
        else
            Console.WriteLine("Failure");
    }
}

outputs failure even though string inherits from object. How can I make this program recognise that list is of type List<T> without knowing what T is?

>Solution :

You can do it with a help of GetGenericTypeDefinition() method to strip generic T from List<T> and have List<> type (note abscence of T and empty <>) to compare with:

if (list.GetType().GetGenericTypeDefinition() == typeof(List<>))
  Console.WriteLine("Success");
else
  Console.WriteLine("Failure");

Fiddle

Leave a ReplyCancel reply