Type conversion issue when setting property through reflection
Because the type long
has an implicit conversion method.
6.1.2 Implicit numeric conversions
You can see implicit conversion method as hidden method that exist behind the =
symbol.
It also work with nullable type:
int i = 0;
int? j = i; // Implicit conversion
long k = i; // Implicit conversion
long? l = i; // Implicit conversion
But going the other way around doesn't work, because no implicit conversion exist to pass a null
to a non-null:
int? i = 0;
int j = i; // Compile assert. An explicit conversion exit...
int k = (int)i; // Compile, but if i is null, you will assert at runtime.
You don't have to explicitly convert a int
to a int?
... or a long?
.
However, when you use reflection, you are bypassing implicit conversion and assign directly the value to the property. This way, you have to convert it explicitly.
info.SetValue(obj, (long?)v, null);
Reflection skip all the sweet stuff hidden behind =
.
When you write:
obj.Value = v;
the compiler knows how to do the proper casting for you and actually compiles
obj.Value = new long?((long) v);
When your use reflection there is no compiler to help you.
Check full article : How to set value of a property using Reflection?
full code if you are setting value for nullable type
public static void SetValue(object inputObject, string propertyName, object propertyVal)
{
//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(propertyType) ? Nullable.GetUnderlyingType(propertyType) : propertyType;
//Returns an System.Object with the specified System.Type and whose value is
//equivalent to the specified object.
propertyVal = Convert.ChangeType(propertyVal, targetType);
//Set the value of the property
propertyInfo.SetValue(inputObject, propertyVal, null);
}
private static bool IsNullableType(Type type)
{
return type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>));
}
you need to convert value like this i.e you need to convert value to your property type like as below
PropertyInfo info = t.GetProperty("Value");
object value = null;
try
{
value = System.Convert.ChangeType(123,
Nullable.GetUnderlyingType(info.PropertyType));
}
catch (InvalidCastException)
{
return;
}
propertyInfo.SetValue(obj, value, null);
you need to do this because you cannot convert any arbirtary value to given type...so you need to convert it like this