Search code examples
c#system.reflection

Reflection GetProperties should exclude unwanted children properties on certain datatype


Surely I am missing the obvious.I am building an internal application and I am reflecting on some of our internal dlls and displaying them in a tree view

Treeview is loaded on demand and for each property when expanded I get the children if any. When children are datetime,string,decimal etc.. I then are expanded once again I should not be getting all the inner properties of a string or datetime and so on . It should not return anything.I have tried few bindingFlags but we no success.

I am using the following method but it's not good enough.

  public static PropertyInfo[] GetPropertiesByType(this Type t)
    {
        if (!t.IsPrimitive
            || t != typeof (System.Decimal)
            || t != typeof (System.String)
              || t != typeof(System.DateTime)
            || t != typeof (System.DateTime?))
        {

            return t.GetProperties(BindingFlags.Public | BindingFlags.Instance)
                .OrderBy(p => p.Name).ToArray();
        }
        return new PropertyInfo[0];
    }

What I want is that when getting Properties it should exclude all the inner properties that a not relevant.

EG Customer has order and order has OrderedDate.When using the treeview I click on customer and I get order click on order and I get OrderDate when clicking orderdate I should have no properties.I get "HasValue and value" and expand value and get all the datetime stuff.

Same when a property is a string I should not see Chars and Length.

Any suggestions


Solution

  • if (!t.IsPrimitive
        || t != typeof (System.Decimal)
        || t != typeof (System.String)
        || t != typeof(System.DateTime)
        || t != typeof (System.DateTime?))
    

    should be

    if (!t.IsPrimitive
        && t != typeof (System.Decimal)
        && t != typeof (System.String)
        && t != typeof(System.DateTime)
        && t != typeof (System.DateTime?))
    

    As is, your conditional will always evaluate to true since all types are either not System.String or not System.Decimal and you are combining them with the OR operator.