I have a third party library which sets a given objects property using reflection as follows. (This is the simplified version)
public void Set(object obj, string prop, object value) {
var propInf = obj.GetType().GetProperty(prop);
value = Convert.ChangeType(value, propInf.PropertyType);
propInf.SetValue(obj, value, null);
}
And We have class with a nullable property
class Test
{
public int? X { get; set; }
}
When I write the following code, it says it cannot convert int
to int?
var t = new Test();
Set(t, "X", 1);
Since Nullable does not implement IConvertible it makes sense. Then I decided to write a method which returns the nullable version of a given value typed object.
public object MakeNullable(object obj) {
if(obj == null || !obj.GetType().IsValueType)
throw new Exception("obj must be value type!");
return Activator.CreateInstance(
typeof(Nullable<>).MakeGenericType(obj.GetType()),
new[] { obj });
}
I hoped to use this method as follows.
var t = new Test();
Set(t, "X", MakeNullable(1));
But it still says it cannot convert int
to int?
. When I debug typeof(Nullable<>).MakeGenericType(obj.GetType())
equals int?
but Activator.CreateInstace
returns an int
value not int?
So this is my case... Any help?