aron
aron

Reputation: 2886

Reflection class to get all properties of any object

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

Upvotes: 8

Views: 22460

Answers (3)

Law Metzler
Law Metzler

Reputation: 1235

The problem with your code is the PayPal Response types are members, NOT properties. Try:

MemberInfo[] memberInfos = 
    thisObject.GetMembers(BindingFlags.Public|BindingFlags.Static|BindingFlags.Instance);

Upvotes: 2

mike
mike

Reputation: 3166

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.

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564333

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.

Upvotes: 7

Related Questions