Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get value of a Nullable Type via reflection

Tags:

c#

reflection

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

like image 967
alfdev Avatar asked Mar 04 '11 13:03

alfdev


People also ask

How do you access the underlying value of a 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.

How do you create a nullable value?

If you've opened a table and you want to clear an existing value to NULL, click on the value, and press Ctrl + 0 .

What happens when we box or unbox nullable types?

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.

What is nullable value type in C#?

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.


1 Answers

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.

like image 160
Marc Gravell Avatar answered Sep 22 '22 15:09

Marc Gravell