How to get Nullable Type value through reflection

Using reflection, I need to get the value of the Nullable Type of DateTime property

How can i do this?

When I try propertyInfo.GetValue(object, null) , it does not work.

THX

My code is:

  var propertyInfos = myClass.GetType().GetProperties(); foreach (PropertyInfo propertyInfo in propertyInfos) { object propertyValue= propertyInfo.GetValue(myClass, null); } 

PropertyValue is always null for type NULL

+7
source share
3 answers

Reflection and Nullable<T> are a bit of a pain; reflection uses object , and Nullable<T> has special box / unpack rules for object . Thus, 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 is sometimes a little confusing and notices that you cannot get the original T from the empty Nullable<T> that was inserted into the box, since all you have is null .

+22
source

Given a simple class:

 public class Foo { public DateTime? Bar { get; set; } } 

And the code:

 Foo foo = new Foo(); foo.Bar = DateTime.Now; PropertyInfo pi = foo.GetType().GetProperty("Bar"); object value = pi.GetValue(foo, null); 
Value

has either null (if .Bar is null) or DateTime. What part of this does not work for you?

0
source

I tried this right now and it worked fine:

 DateTime? d = DateTime.Now; var dt = typeof(DateTime?); Console.WriteLine(dt.GetMethod("ToString").Invoke(d, null)); 
0
source

All Articles