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
}
}
note I’m assuming you mean
Nullable<T>; if you meanNullable<T>or a reference, then you already have it:object(fromGetValue) – just check fornull.In the case of
Nullable<T>; you can’t cast to a single non-generic type (other thanobject) – but you don’t need to; just check that it isn’tnull, since emptyNullable<T>is boxed tonull, andGetValuereturnsobject(hence it boxes the value).To clarify,
Nullableis a static utility class that is completely separate to theNullable<T>struct; so you don’t cast toNullableat all. As it happens,Nullableexists to provide things like theGetUnderlyingTypethat helps you work withNullable<T>.