List all properties of a C#object?

Asked

Viewed 2,062 times

2

I need to write all the primitive properties of a C# object regardless of how many "levels" I enter these objects.

I have the following object in Javascript:

var objeto = {
  propriedade:{
    valor:42
  },
  atributo:"foo"  
}

So to access all of his properties recursively, I do the following:

function PrintAllProperties(obj){
      for(var prop in obj){
          if(typeof obj[prop]==="object")
             PrintAllProperties(obj[prop]);
          else
             console.log(obj[prop]);
         }
} PrintAllProperties(objeto);

Thus the output is formed by all properties with primitive value no matter the amount of levels that had to be accessed from that "parent object" ( working example )

How to do this in C#?

1 answer

3


It would be something like that:

public void PrintProperties(object obj, int indent)
{    
    if (obj == null) return;
    string indentString = new string(' ', indent);
    Type objType = obj.GetType();
    PropertyInfo[] properties = objType.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
    foreach (PropertyInfo property in properties)
    {
        object propValue = property.GetValue(obj, null);
        var elems = propValue as IList;
        if (elems != null)
        {
            foreach (var item in elems)
            {
                PrintProperties(item, indent + 3);
            }
        }
        else
        {
            if (property.PropertyType.Assembly == objType.Assembly)
            {
                Console.WriteLine("{0}{1}:", indentString, property.Name);

                PrintProperties(propValue, indent + 2);
            }
            else
            {
                Console.WriteLine("{0}{1}: {2}", indentString, property.Name, propValue);
            }
        }
    }
}

I took it from here, with some modifications. This prints the properties, indenting in console.

  • Note that this will only list public properties.

  • @dcastro I put with all the BindingFlags. I hope I haven’t forgotten anything. Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.