This is within a .NET Core 1.1.4 project, so please take this into consideration.
I'm trying to create a function that would verify if a value can be assigned to a type, but I'm encountering an issue 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 above handles the case if value
is null
, and attempts to verify that the destinationType
is Nullable<T>
; the else
clause handles if value
actually contains something, so it attempts to determine if you can assign it to destinationType
or, if it's a Nullable<T>
, that it's assignable to T
.
The problem is that Nullable<T>
isn't a Type
, so calling CheckIfAssignable(3, Nullable<Int32>)
doesn't match the function signature.
Changing the signature to:
protected void CheckIsAssignable(Object value, ValueType destinationType)
lets me pass a Nullable<T>
, but then I can't submit it as an argument to Nullable.GetUnderlyingType
.
I'm not sure if I've over-complicated the issue with this, but I feel there is a simple solution that I'm just not seeing.
You are not passing the type itself there. You need to use the typeof()
command like so:
CheckIfAssignable(3, typeof(Nullable<Int32>))