-2

I would like to access all string properties of an object that has defined classes which also have properties of string type to apply a certain treatment. For example :

public class Class1 
{ 
   public string String1 {get; set;}
   public Class2 class2 {get; set;}
}

public class Class2 
{ 
   public string String2 {get; set;}
}

Here, I would like to have a property list which contains String1 and String2

For the moment I know how to access to String1 :

var instanceOfClass1 =  new Class1();
var stringsList = instanceOfClass1.GetType().GetProperties().Where(prop => prop.PropertyType == typeof(string));

But this won't access to String2.

Thank you in advance if you have any idea.

InUser
  • 1,138
  • 15
  • 22
Alchoder
  • 61
  • 5
  • Make it a method and pass the objects you want to query to it. – Tanveer Badar Aug 04 '20 at 07:10
  • Check this answer. https://stackoverflow.com/a/20554474/9695286 – Karan Aug 04 '20 at 07:17
  • @TheGeneral , thanks, this gives me ideas but I'm looking for a more generic way to do so, I might have more than one property which is a defined class with string properties, and I would like to apply it to an instance main object – Alchoder Aug 04 '20 at 07:29

1 Answers1

2

You can use a recursive method that yields every property of the needed type

public static IEnumerable<PropertyInfo> GetProp<T>(object Obj)
{
    if (Obj is object)
    {
        foreach (var prop in Obj.GetType().GetProperties())
        {
            if (prop.PropertyType == typeof(T))
            {
                yield return prop;
            }
            else
            {
                foreach (var t in GetProp<T>(prop.GetValue(Obj)))
                    yield return t;
            }
        }
    }
}

public class Class1 
{ 
   public string String1 {get; set;}
   public Class2 class2 {get; set;}
}

public class Class2 
{ 
   public string String2 {get; set;}
    public Class3 class3 {get; set;}
}

public class Class3
{ 
   public string String3 {get; set;}
    public int int3 {get; set;}
}

var instanceOfClass1 =  new Class1
{
    class2 = new Class2
    {
        class3 = new Class3()
    }
};
        
foreach (var prop in GetProp<string>(instanceOfClass1))
{
    Console.WriteLine(prop);
}

This outputs :

System.String String1
System.String String2
System.String String3

Note that circular reference will end up with infinite loop/Stack Overflow :

public class Class1 
{ 
   public string String1 {get; set;}
   public Class2 class2 {get; set;}
    
    public Class1()
    {
        class2 = new Class2(this);
    }
}

public class Class2 
{ 
   public string String2 {get; set;}
    public Class1 class1 {get; set;}
    
    public Class2(Class1 class1)
    {
        this.class1 = class1;
    }
}
Cid
  • 14,968
  • 4
  • 30
  • 45