tags:

views:

53

answers:

2

Hello, I need to make a function that get all the properies of an object (including an children objects) This is for my error logging feature. Right now my code always returns 0 properties. Please let me know what I'm doing wrong, thanks!

public static string GetAllProperiesOfObject(object thisObject)
{
    string result = string.Empty;
    try
    {
        // get all public static properties of MyClass type
        PropertyInfo[] propertyInfos;
        propertyInfos = thisObject.GetType().GetProperties(BindingFlags.Public | BindingFlags.Static);//By default, it will return only public properties.
        // sort properties by name
        Array.Sort(propertyInfos,
                   (propertyInfo1, propertyInfo2) => propertyInfo1.Name.CompareTo(propertyInfo2.Name));

        // write property names
        StringBuilder sb = new StringBuilder();
        sb.Append("<hr />");
        foreach (PropertyInfo propertyInfo in propertyInfos)
        {
            sb.AppendFormat("Name: {0} | Value: {1} <br>", propertyInfo.Name, "Get Value");
        }
        sb.Append("<hr />");
        result = sb.ToString();
    }
    catch (Exception exception)
    {
        // to do log it
    }

    return result;
}

here's what the object looks like: alt text alt text

+2  A: 

If you want all of the properties, try:

propertyInfos = thisObject.GetType().GetProperties(
      BindingFlags.Public | BindingFlags.NonPublic // Get public and non-public
    | BindingFlags.Static | BindingFlags.Instance  // Get instance + static
    | BindingFlags.FlattenHierarchy); // Search up the hierarchy

For details, see BindingFlags.

Reed Copsey
Hi Reed, thanks. I added this but I still get 0 properties. I added images to my questions, see above. thanks!
aron
A: 

Your propertyInfos array is returning 0 length for one of my classes. Changing the line to be

propertyInfos = thisObject.GetType().GetProperties();

Results in it being populated. Therefore, this line of code is your problem. It appears if you add the flag

BindingFlags.Instance

to your parameters it will return the same properties as the parameterless call. Does adding this parameter to your list fix the problem?

EDIT: Just saw your edit. Based on the code you posted, it didn't work for me either. Adding the BindingFlags.Instance made it return properties for me. I'd suggest posting the exact code you are having trouble with as your screenshot shows different code.

mrnye
hi, the above code is my current code. In the screen-shot I tried Reed Copsey's suggestion.
aron
can you try the code on a simpler object to see if it works? If not, can you post the code of the class you are trying it on?
mrnye