Using reflection I need to retrieve the value of a propery of a Nullable Type of DateTime
How can I do this?
When I try propertyInfo.GetValue(object, null)
it does not function.
thx
My code:
var propertyInfos = myClass.GetType().GetProperties();
foreach (PropertyInfo propertyInfo in propertyInfos)
{
object propertyValue= propertyInfo.GetValue(myClass, null);
}
propertyValue result always null for nullable type
If you want to use the default value of the underlying value type in place of null , use the Nullable<T>. GetValueOrDefault() method. At run time, if the value of a nullable value type is null , the explicit cast throws an InvalidOperationException.
If you've opened a table and you want to clear an existing value to NULL, click on the value, and press Ctrl + 0 .
Boxing a value of a nullable-type produces a null reference if it is the null value (HasValue is false), or the result of unwrapping and boxing the underlying value otherwise. will output the string “Box contains an int” on the console.
The Nullable type allows you to assign a null value to a variable. Nullable types introduced in C#2.0 can only work with Value Type, not with Reference Type. The nullable types for Reference Type is introduced later in C# 8.0 in 2019 so that we can explicitly define if a reference type can or can not hold a null value.
Reflection and Nullable<T>
are a bit of a pain; reflection uses object
, and Nullable<T>
has special boxing/unboxing rules for object
. So by the time you have an object
it is no longer a Nullable<T>
- it is either null
or the value itself.
i.e.
int? a = 123, b = null;
object c = a; // 123 as a boxed int
object d = b; // null
This makes it a bit confusing sometimes, and note that you can't get the original T
from an empty Nullable<T>
that has been boxed, as all you have is a null
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With