Reputation: 33867
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
}
}
Upvotes: 19
Views: 11826
Reputation: 1064114
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>
.
Upvotes: 32
Reputation: 63378
Since you've established that the property is of type Nullable<something>
, you know its value has a HasValue
property - so find that property by reflection and get its value.
Upvotes: 0