A Comprehensive Guide to Accessing Generic Class Properties via Reflection

Dec 07, 2025 · Programming · 12 views · 7.8

Keywords: C# Reflection | Generic Classes | Property Access | GetProperty Method | IList Interface

Abstract: This article provides an in-depth exploration of how to retrieve property values from generic class objects in C# using reflection, particularly when type parameters are unknown. It analyzes the working principles of the GetProperty method, offers complete code examples, and explains proper handling of generic types and interface conversions. Through practical demonstrations, readers will master key techniques for safely accessing generic properties in dynamic type scenarios.

Reflection Mechanism and Generic Class Property Access

In C# programming, when dealing with generic class objects where type parameters are unknown, direct type casting becomes infeasible. Reflection provides powerful capabilities for dynamically accessing type information. This article analyzes in detail how to retrieve the value of the Items property from generic class Foo<T> through reflection, based on practical development scenarios.

Problem Analysis and Core Challenges

Consider the following generic class definition:

class Foo<T>
{
    public List<T> Items { get; set; }
}

When an object obj exists with a runtime type of Foo<int> or other concrete type instances, but only object type is known at compile time. Directly calling obj.GetType().GetProperty("Items") may return null, due to the special handling of generic types in reflection.

Solution Implementation

The correct reflection access method is as follows:

Type t = obj.GetType();
PropertyInfo prop = t.GetProperty("Items");
object list = prop.GetValue(obj);

This code first obtains the object's runtime type, then searches for the property named "Items" through the GetProperty method. If the property exists, the GetValue method returns its current value. Note that since the type parameter T is unknown, the return value can only be of type object.

Complete Example and Interface Conversion

The following is a complete demonstration program:

class Program
{
    static void Main()
    {   
        Foo<int> fooObject = new Foo<int>();
        fooObject.Items = new List<int> { 1, 2, 3};
        object obj = (object)fooObject;

        PropertyInfo propInfo = obj.GetType().GetProperty("Items");
        object itemValue = propInfo.GetValue(obj, null);

        Console.WriteLine(itemValue);
        // Output: System.Collections.Generic.List`1[System.Int32]

        IList values = (IList)itemValue;
        foreach(var val in values)
            Console.WriteLine(val); // Output: 1, 2, 3
    }
}

Although the return value cannot be directly cast to List<T>, it can be safely converted to the IList interface, since List<T> implements this non-generic interface. This allows iteration over the collection without knowing the specific type parameter.

Technical Key Points Summary

1. Reflection's GetProperty method can correctly identify properties in generic classes, provided the object's actual runtime type is used rather than the generic definition type.

2. Conversion via the IList interface is an effective strategy for handling unknown generic collections, providing type-safe collection operations.

3. This approach is applicable to various generic type scenarios, including nested generics or complex type parameters.

Performance and Alternative Considerations

While reflection offers flexibility, its performance overhead should be noted. In performance-sensitive scenarios, consider the following alternatives:

However, when types are completely unknown and maximum flexibility is required, reflection remains the most direct and effective solution.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.