C#
generics
type checking
programming
tutorial

Testing if object is of generic type in C

Object-Oriented Design practice on Codemia

Turn requirements into classes, and defend the design, on the problems that come up in OOD rounds.

Practice OOD

Introduction

Testing if an object is of a generic type in C# requires reflection because generic types have two forms: open (List<>) and closed (List<int>). The is keyword and pattern matching work for closed generic types but not open ones. To check if an object is any List<T> regardless of T, use obj.GetType().GetGenericTypeDefinition() == typeof(List<>). This is essential for building serializers, dependency injection containers, and any framework code that needs to inspect types at runtime.

Checking Closed Generic Types

csharp
1var numbers = new List<int> { 1, 2, 3 };
2
3// These work — checking against a specific closed type
4bool isList = numbers is List<int>;        // true
5bool isListStr = numbers is List<string>;  // false
6
7// Pattern matching (C# 7+)
8if (numbers is List<int> intList)
9{
10    Console.WriteLine(intList.Count);  // 3
11}
12
13// typeof comparison
14Console.WriteLine(numbers.GetType() == typeof(List<int>));     // true
15Console.WriteLine(numbers.GetType() == typeof(List<string>));  // false

Closed generic types have all type parameters specified. Standard is, as, and typeof work normally for these.

Checking Open Generic Types

csharp
1var numbers = new List<int> { 1, 2, 3 };
2var names = new List<string> { "Alice", "Bob" };
3var dict = new Dictionary<string, int> { ["a"] = 1 };
4
5// Cannot do: numbers is List<>  — compile error!
6// Cannot do: typeof(numbers) == typeof(List<>)
7
8// Use GetGenericTypeDefinition() to get the open type
9bool isAnyList = numbers.GetType().IsGenericType
10    && numbers.GetType().GetGenericTypeDefinition() == typeof(List<>);
11// true — it's a List<something>
12
13bool isAnyDict = dict.GetType().IsGenericType
14    && dict.GetType().GetGenericTypeDefinition() == typeof(Dictionary<,>);
15// true — it's a Dictionary<something, something>
16
17// Helper method
18static bool IsOfGenericType(object obj, Type genericType)
19{
20    var type = obj.GetType();
21    return type.IsGenericType
22        && type.GetGenericTypeDefinition() == genericType;
23}
24
25Console.WriteLine(IsOfGenericType(numbers, typeof(List<>)));        // true
26Console.WriteLine(IsOfGenericType(names, typeof(List<>)));          // true
27Console.WriteLine(IsOfGenericType(dict, typeof(Dictionary<,>)));    // true
28Console.WriteLine(IsOfGenericType(numbers, typeof(Dictionary<,>))); // false

typeof(List<>) is the open generic type definition. GetGenericTypeDefinition() strips the type arguments from a closed generic type, returning the open form for comparison.

Getting the Type Arguments

csharp
1var dict = new Dictionary<string, int>();
2
3Type type = dict.GetType();
4if (type.IsGenericType)
5{
6    Type[] typeArgs = type.GetGenericArguments();
7    Console.WriteLine($"Key type: {typeArgs[0].Name}");    // String
8    Console.WriteLine($"Value type: {typeArgs[1].Name}");  // Int32
9}
10
11// Practical use: generic serialization
12static string DescribeCollection(object obj)
13{
14    var type = obj.GetType();
15    if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
16    {
17        var elementType = type.GetGenericArguments()[0];
18        var count = (int)type.GetProperty("Count").GetValue(obj);
19        return $"List of {elementType.Name} with {count} elements";
20    }
21    return "Not a generic list";
22}
23
24Console.WriteLine(DescribeCollection(new List<int> { 1, 2, 3 }));
25// "List of Int32 with 3 elements"

Checking Generic Interfaces

csharp
1// Check if an object implements IEnumerable<T> for any T
2static bool ImplementsGenericInterface(object obj, Type genericInterface)
3{
4    return obj.GetType().GetInterfaces().Any(i =>
5        i.IsGenericType &&
6        i.GetGenericTypeDefinition() == genericInterface);
7}
8
9var list = new List<int>();
10var dict = new Dictionary<string, int>();
11var array = new int[] { 1, 2, 3 };
12
13Console.WriteLine(ImplementsGenericInterface(list, typeof(IEnumerable<>)));  // true
14Console.WriteLine(ImplementsGenericInterface(dict, typeof(IDictionary<,>))); // true
15Console.WriteLine(ImplementsGenericInterface(array, typeof(IEnumerable<>))); // true
16
17// Get the specific type argument from the interface
18static Type GetGenericInterfaceArgument(object obj, Type genericInterface)
19{
20    var iface = obj.GetType().GetInterfaces().FirstOrDefault(i =>
21        i.IsGenericType &&
22        i.GetGenericTypeDefinition() == genericInterface);
23    return iface?.GetGenericArguments()[0];
24}
25
26Type elementType = GetGenericInterfaceArgument(list, typeof(IEnumerable<>));
27Console.WriteLine(elementType.Name);  // Int32

Checking Inheritance with Generic Base Classes

csharp
1public class Repository<T> { }
2public class UserRepository : Repository<User> { }
3
4var repo = new UserRepository();
5
6// Direct type check fails for the base generic
7Console.WriteLine(repo is Repository<User>);  // true (closed type)
8// Cannot check: repo is Repository<>
9
10// Walk the inheritance chain
11static bool InheritsFromGeneric(Type type, Type genericBase)
12{
13    while (type != null && type != typeof(object))
14    {
15        var current = type.IsGenericType
16            ? type.GetGenericTypeDefinition()
17            : type;
18        if (current == genericBase)
19            return true;
20        type = type.BaseType;
21    }
22    return false;
23}
24
25Console.WriteLine(InheritsFromGeneric(repo.GetType(), typeof(Repository<>)));
26// true

Practical Example: Dependency Injection

csharp
1// Register and resolve open generic types
2var services = new ServiceCollection();
3
4// Register open generic
5services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
6
7// At resolution time, the DI container checks if the requested type
8// matches the open generic and constructs the closed type:
9// IRepository<User> → Repository<User>
10// IRepository<Order> → Repository<Order>
11
12// Manual equivalent:
13static object CreateInstance(Type openGenericType, Type typeArgument)
14{
15    Type closedType = openGenericType.MakeGenericType(typeArgument);
16    return Activator.CreateInstance(closedType);
17}
18
19var userRepo = CreateInstance(typeof(Repository<>), typeof(User));
20Console.WriteLine(userRepo.GetType().Name);  // Repository`1

Common Pitfalls

  • Using is or as with open generic types: obj is List<> is a compile error. C# does not support pattern matching against open generic types. You must use GetGenericTypeDefinition() via reflection for open type checks.
  • Forgetting to check IsGenericType first: Calling GetGenericTypeDefinition() on a non-generic type throws InvalidOperationException. Always guard with type.IsGenericType before calling GetGenericTypeDefinition().
  • Not walking the inheritance chain: obj.GetType().GetGenericTypeDefinition() == typeof(Repository<>) only checks the exact runtime type, not base classes. If UserRepository : Repository<User>, this check returns false for UserRepository. Walk BaseType up the chain to find generic base classes.
  • Confusing typeof(List<>) with typeof(List<object>): typeof(List<>) is the open generic type definition. typeof(List<object>) is a closed type with object as the argument. They are not equal, and checking against List<object> does not match List<int>.
  • Performance overhead of reflection: GetType(), GetGenericTypeDefinition(), and GetInterfaces() involve reflection, which is slower than direct type checks. Cache results when performing type checks in hot paths (loops, serialization).

Summary

  • Use is and pattern matching for closed generic types (List<int>, Dictionary<string, int>)
  • Use GetGenericTypeDefinition() == typeof(List<>) for open generic type checks
  • Always check IsGenericType before calling GetGenericTypeDefinition() to avoid exceptions
  • Use GetGenericArguments() to extract the type parameters from a closed generic type
  • Walk BaseType up the inheritance chain to check against generic base classes
  • Check GetInterfaces() to test if an object implements a specific generic interface

Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Object-Oriented Design practice on Codemia

Turn requirements into classes, and defend the design, on the problems that come up in OOD rounds.

Practice OOD