CBC_NS
CBC_NS

Reputation: 1957

Get all DateTime and Nullable<DateTime> properties in T obj using reflection

I am trying to get all DateTime and Nullable< DateTime > properties of an object. I am using the following lamda expression, but it returns 0 results. What is the correct way of doing this?

Type t = obj.GetType();

// Loop through the properties.
PropertyInfo[] props = t.GetProperties()
    .Where(p => p.GetType() == typeof(DateTime) || p.GetType() == typeof(Nullable<DateTime>)).ToArray();

Upvotes: 2

Views: 1361

Answers (1)

DavidG
DavidG

Reputation: 119017

p.GetType() will give you the type of p which is always PropertyInfo. Instead you should be using p.PropertyType. For example:

Type t = obj.GetType();

//It's a little nicer to keep the types you're searching on 
//in a list and compare using Contains():
var types = new[] { typeof(DateTime), typeof(Nullable<DateTime>) };

PropertyInfo[] props = t.GetProperties()
    .Where(p => types.Contains(p.PropertyType))
    .ToArray();

Upvotes: 4

Related Questions