Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading