0

In c# I have a class with properties on it which returns IEnumerables.

public class MyClass
{
   public IEnumerable<MyPropClass1> Prop1 { get { return _prop1; } }
   public IEnumerable<MyPropClass2> Prop2 { get { return _prop2; } }
   public IEnumerable<AnotherClassAltogether> Prop3 {get {return _prop3; } }
   ...
}

Lets say MyPropClass1 and MyPropClass2 both inherit from MyPropBaseClass but AnotherClassAltogether doesn't.

What is the simplest way to get all properties from MyClass which either are an IEnumerable of a certain class, or an IEnumerable of a class which is somewhere down the chain is inherited from that class?

E.g. if I wanted to query MyClass for properties based on IEnumerables templated to something that is based on MyPropBaseClass then it should return Prop1 and Prop2

For more clarity (hopefully to address the close vote) a pseudo function to answer this question would be something like:

var properties = GetIEnumerablePropertiesOfType(typeof(MyClass), typeof(MyPropBaseClass))

and this would return a list of properties containing Prop1 and Prop2 (as an enumerable of System.Reflection.PropertyInfo)

Jonny
  • 796
  • 2
  • 10
  • 23

1 Answers1

1
using System;
using System.Reflection;    
using System.Linq;
using System.Collections;
using System.Collections.Generic;

public class Program
{
    public class MyPropClass{}
    public class MyPropClass1 : MyPropClass{}
    public class MyPropClass2 : MyPropClass{}
    public class AnotherClassAltogether {}

    public class MyClass
    {
         public object Prop_Wrong { get; set; }
         public IEnumerable Prop_Wrong_IEnumerable { get; set; }
         public IEnumerable<MyPropClass1> Prop1 { get; set; }
         public IEnumerable<MyPropClass2> Prop2 { get; set; } 
         public IEnumerable<AnotherClassAltogether> Prop3 {get; set; }
    }

    public static IEnumerable<PropertyInfo> GetIEnumerablePropertiesOfType(Type targetType, Type lookFor)
    {
        return targetType.GetProperties(BindingFlags.Public | BindingFlags.Instance)
            .Where(x => x.PropertyType.IsGenericType
                     && x.PropertyType.GetGenericTypeDefinition() == typeof(IEnumerable<>)
                     && x.PropertyType.GenericTypeArguments.Single().IsAssignableTo(lookFor));
    }

    public static void Main()
    {
        foreach (var item in GetIEnumerablePropertiesOfType(typeof(MyClass), typeof(MyPropClass)))
        {
            Console.WriteLine($"Property {item.Name} of type {item.PropertyType}");
        }
    }
}
Andriy Shevchenko
  • 1,117
  • 6
  • 21