How to get all properties of a class with generic type parameter

586 Views Asked by At

See the following example. When having properties where the property type is a class with a generic type parameter, how can I list all those properties regardless of generic type parameter?

class Program
{
    public static VehicleCollection<Motorcycle> MotorcycleCollection { get; set; }
    public static VehicleCollection<Car> CarCollection { get; set; }
    public static VehicleCollection<Bus> BusCollection { get; set; }

    static void Main(string[] args)
    {
        MotorcycleCollection = new VehicleCollection<Motorcycle>();
        CarCollection = new VehicleCollection<Car>();
        BusCollection = new VehicleCollection<Bus>();

        var allProperties = typeof(Program).GetProperties().ToList();
        Console.WriteLine(allProperties.Count);  // Returns "3".
        var vehicleProperties = typeof(Program).GetProperties().Where(p => 
            p.PropertyType == typeof(VehicleCollection<Vehicle>)).ToList();
        Console.WriteLine(vehicleProperties.Count);  // Returns "0".
        Console.ReadLine();
    }
}

public class VehicleCollection<T> where T : Vehicle
{
    List<T> Vehicles { get; } = new List<T>();
}

public abstract class Vehicle
{
}

public class Motorcycle : Vehicle
{
}

public class Car : Vehicle
{
}

public class Bus : Vehicle
{
}
1

There are 1 best solutions below

1
On BEST ANSWER

You can use the GetGenericTypeDefinition method to get the open form of the generic type and then compare that to VehicleCollection<> (the open form) like this:

var vehicleProperties = typeof(Program).GetProperties()
    .Where(p =>
        p.PropertyType.IsGenericType &&
        p.PropertyType.GetGenericTypeDefinition() == typeof(VehicleCollection<>))
    .ToList();

IsGenericType is used to make sure that the property type is generic.