casting - Cast from unknown type in c# -
i have object contain value in string , origin type in field.
class myclass { public string value; public type type; } myclass s=new myclass(); s.value = "10"; s.type = typeof(int); type tt = s.type; row.value[ind]= s[0].value tt; //i have error here
how can cast value that's type.
basically scenario want type cast type stored in variable. can @ runtime :
myclass s=new myclass(); s.value = "10"; s.type = typeof(int); var val = convert.changetype(s.value, s.type);
but since conversion done @ runtime, cannot store variable val in integeral collection i.e. list<int>
or cannot int = val
, coz @ complie time, type not known yet, , have compilation error, again same obvious reason.
in little complex scenario, if had typecast user-defined datatype
, wanted access different properties, cannot is. let me demonstrate few modifications code :
class myclass { public object value; public type type; }
and have another:
class mycustomtype { public int id { get; set; } }
now :
myclass s = new myclass(); s.value = new mycustomtype() { id = 5 }; s.type = typeof(mycustomtype); var val = convert.changetype(s.value, s.type);
now if val.id
, won't compile. must retrieve either using dynamic keyword or reflection below:
var id = val.gettype().getproperty("id").getvalue(val);
you can iterate on available properties of customtype (class) , retrieve values.
for retrieving through dynamic
keyword, directly this:
dynamic val = convert.changetype(s.value, s.type); int id = val.id;
and compiler won't cry. (yes there won't intellisense though)
Comments
Post a Comment