Passing `Nullable <T>` as a parameter type of a C # function
This is part of the .NET Core 1.1.4 project, so please keep this in mind.
I am trying to create a function that checks whether it is possible to assign a value to a type, but I am facing a problem with Nullable<T> types.
My function:
protected void CheckIsAssignable(Object value, Type destinationType) { if (value == null) { // Nullable.GetUnderlyingType returns null for non-nullable types. if (Nullable.GetUnderlyingType(destinationType) == null) { var message = String.Format( "Property Type mismatch. Tried to assign null to type {0}", destinationType.FullName ); throw new TargetException(message); } } else { // If destinationType is nullable, we want to determine if // the underlying type can store the value. if (Nullable.GetUnderlyingType(destinationType) != null) { // Remove the Nullable<T> wrapper destinationType = Nullable.GetUnderlyingType(destinationType); } // We can now verify assignability with a non-null value. if (!destinationType.GetTypeInfo().IsAssignableFrom(value.GetType())) { var message = String.Format( "Tried to assign {0} of type {1} to type {2}", value, value.GetType().FullName, destinationType.FullName ); throw new TargetException(message); } } } The if clause shows an example if value is null , and tries to verify that destinationType is Nullable<T> ; the else handles if value really contains something, so it tries to determine if you can assign it to destinationType or if it is Nullable<T> , which it assigns to T
The problem is that Nullable<T> not Type , so the call to CheckIfAssignable(3, Nullable<Int32>) does not match the function signature.
Signature change to:
protected void CheckIsAssignable(Object value, ValueType destinationType) allows me to pass a Nullable<T> , but then I cannot present it as an argument to Nullable.GetUnderlyingType .
I'm not sure that I have complicated the problem too much, but I feel that there is a simple solution that I just cannot see.