In an application I have some code that has a FieldInfo for a Nullable<int> and I need to retrieve the nullable value (not the underlying value) like in the sample bellow:
class Test
{
public int? value;
}
public class Program
{
static void Main(string[] args)
{
var obj = new Test { value = 10 };
var fld = typeof (Test).GetField("value");
var v = fld.GetValue(obj);
System.Diagnostics.Debug.WriteLine(v.GetType().FullName);
System.Diagnostics.Debug.WriteLine(fld.FieldType.FullName);
}
}
My problem is that v is always assigned the underlying value (in this sample an int) instead the nullable (in this sample a Nullable<int>).
PS: The real application don’t has the type of the nullable at compile time, so a cast is not possible.
Thanks in advance for any help.
In this case
vis of typeobject. Ifvalueis null thenvwill be null; ifvalueis some integer thenvwill be that integer. If you wantvto actually have the typeNullable<int>then you have to declare it as such:var v = (int?) fld.GetValue(obj);.If you need to be able to reference
v.Valueand get the boxed value back, you’ll probably have to record the fact thatfldwas nullable (Nullable.GetUnderlyingType(fld.FieldType) != null). Note that generics will not help you here because you do not know theTat compile time.Here’s a helper you can use:
Then instead of calling
var v = fld.GetValue(obj);, sayvar v = fld.GetNullableValue(obj);. Iffldrepresents a Nullable type, you’ll get an object with aValueproperty; if not, you’ll just get the value.