c# - Nullable problems with Activator.CreateInstance and Convert.ChangeType -
i have third party library sets given objects property using reflection follows. (this 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 have class nullable property
class test { public int? x { get; set; } }
when write following code, says cannot convert int
int?
var t = new test(); set(t, "x", 1);
since nullable not implement iconvertible makes sense. decided write method returns nullable version of given value typed object.
public object makenullable(object obj) { if(obj == null || !obj.gettype().isvaluetype) throw new exception("obj must value type!"); return activator.createinstance( typeof(nullable<>).makegenerictype(obj.gettype()), new[] { obj }); }
i hoped use method follows.
var t = new test(); set(t, "x", makenullable(1));
but still says cannot convert int
int?
. when debug typeof(nullable<>).makegenerictype(obj.gettype())
equals int?
activator.createinstace
returns int
value not int?
so case... help?
this should work:
public static object changetype(object value, type conversiontype) { if (conversiontype.isgenerictype && conversiontype.getgenerictypedefinition() == typeof(nullable<>)) { if (value == null) return null; var nullableconverter = new nullableconverter(conversiontype); conversiontype = nullableconverter.underlyingtype; } return convert.changetype(value, conversiontype); }