tags:

views:

39

answers:

3

I'm reflecting on an object and only want the public properties of an instance, I don't want public static properties. The problem is GetProperties() returns both static and instance public properties. Anyone have an idea how to best approach this problem?

private IOrderedEnumerable<PropertyInfo> GetSortedPropInfos()
{
    return dataExtractor.GetType().GetProperties().OrderBy(
            p => p.Name );
}

Note, I sort the list since GetProperties() does not specify any type of ordering, and ordering is important to me.

A: 

Use the other overload of GetProperties, which allows you to specify binding flags such as BindingFlags.Instance.

return dataExtractor.GetType().GetProperties(
        BindingFlags.Instance | BindingFlags.Public).OrderBy(
        p => p.Name );
Heinzi
+1  A: 
private IOrderedEnumerable<PropertyInfo> GetSortedPropInfos()
{
    return dataExtractor.GetType()
                        .GetProperties(BindingFlags.Instance | BindingFlags.Public)
                        .OrderBy( p => p.Name );
}
BFree
Thanks, works great.
Martin Jasper
A: 

Yep, you need to set the binding flags in the constructor. The binding flags specify flags that control binding and the way in which the search for members and types is conducted by reflection. Take a look at the following for more information:

BindingFlags Enumeration: http://msdn.microsoft.com/en-us/library/system.reflection.bindingflags.aspx

atconway
Very helpful link, thanks.
Martin Jasper