[ACCEPTED]-How to get value of a Nullable Type via reflection-reflection
Accepted answer
Reflection and Nullable<T>
are a bit of a pain; reflection 7 uses object
, and Nullable<T>
has special boxing/unboxing 6 rules for object
. So by the time you have an object
it 5 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 4 it a bit confusing sometimes, and note that 3 you can't get the original T
from an empty 2 Nullable<T>
that has been boxed, as all you have is 1 a null
.
Given 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 3 either null (if .Bar is null) or the DateTime 2 value. What part of this isn't working 1 for you?
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.