22

I have a question on how to determine an object's Nullable property type.

ObjectA has a property DateTime? CreateDate;

When I iterate through its properties like the following code, how do I check if a property is a Nullable DateTime type?

foreach (PropertyInfo pi in ObjectA.GetType().GetProperties())
{
    //do the compare here
}
CarenRose
  • 1,266
  • 1
  • 12
  • 24
Eatdoku
  • 6,569
  • 13
  • 63
  • 98

3 Answers3

54
pi.PropertyType == typeof(DateTime?)
Pavel Minaev
  • 99,783
  • 25
  • 219
  • 289
  • another question thou... how do I do switch based on the type? do i have to use fullname instead? or should be using "If" statement instead? what's the string FullName for a Nullable DateTime type? thank you – Eatdoku Jul 25 '09 at 17:28
  • 1
    I would strongly advise you to use `if`, and avoid `FullName`. If you want to see `FullName` for `DateTime?`, then just print out `typeof(DateTime?).FullName` - but it's going to be lengthy, will make your code less readable, be brittle (what if you occasionally delete a character somewhere?), and will result in slower comparisons (`Type` objects themselves are compared by reference - i.e. there's at most one `Type` object for any given, so if two references are equal, then this is the same type; and such comparison is fast) – Pavel Minaev Jul 25 '09 at 19:28
4
pi.PropertyType == typeof(Nullable<DateTime>);
Manish Basantani
  • 16,931
  • 22
  • 71
  • 103
0

Try:

property.PropertyType.Equals(typeof(DateTime?))