Kalai
Kalai

Reputation: 297

How to use the Convert.ChangeType(value, type) when the value is nullable

I got an exception , when i am trying to convert the value to given type, but value holds null value.

//find out the type
Type type = inputObject.GetType();

//get the property information based on the type
System.Reflection.PropertyInfo propertyInfo = type.GetProperty(propertyName);

//find the property type
Type propertyType = propertyInfo.PropertyType;

//Convert.ChangeType does not handle conversion to nullable types
//if the property type is nullable, we need to get the underlying type of the property
var targetType = IsNullableType(propertyInfo.PropertyType) ? Nullable.GetUnderlyingType(propertyInfo.PropertyType) : propertyInfo.PropertyType;

//Returns an System.Object with the specified System.Type and whose value is
//equivalent to the specified object.
propertyVal = Convert.ChangeType(propertyVal, targetType);

Here, propertyVal = holds null value, so its throws an exception.

InvalidCastException: Null object cannot be converted to a value type.

If there any way to fix this issue.

Upvotes: 2

Views: 3383

Answers (1)

Dmitry Pavlushin
Dmitry Pavlushin

Reputation: 612

The simpliest thing you can do is just

propertyVal = (propertyVal == null) ? null : Convert.ChangeType(propertyVal, targetType);

Upvotes: 2

Related Questions