Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflection - check all nullable properties have values

I have to loop through all the properties in a few classes and check any nullable properties to see if they have a value. How do I cast the value returned from propertyInfo.GetValue() to a generic nullable type so that I can check the HasValue property?

Code snipped for brevity:

foreach (PropertyInfo propInfo in this.GetType().GetProperties())
{
    if (<Snip: Check to see that this is a nullable type>)                                                                      
    {
           //How do i cast this properly in here to allow me to do:
           if(!((Nullable)propInfo.GetValue(this, null)).HasValue)
                  //More code here
    }
}
like image 664
Paddy Avatar asked Jan 20 '10 12:01

Paddy


1 Answers

note I'm assuming you mean Nullable<T>; if you mean Nullable<T> or a reference, then you already have it: object (from GetValue) - just check for null.

In the case of Nullable<T>; you can't cast to a single non-generic type (other than object) - but you don't need to; just check that it isn't null, since empty Nullable<T> is boxed to null, and GetValue returns object (hence it boxes the value).

if(Nullable.GetUnderlyingType(propInfo.PropertyType) != null) {
    // it is a Nullable<T> for some T
    if(propInfo.GetValue(this, null) != null) {
        // it has a value (it isn't an empty Nullable<T>)
    }
}

To clarify, Nullable is a static utility class that is completely separate to the Nullable<T> struct; so you don't cast to Nullable at all. As it happens, Nullable exists to provide things like the GetUnderlyingType that helps you work with Nullable<T>.

like image 133
Marc Gravell Avatar answered Nov 15 '22 14:11

Marc Gravell