C# Reflection DateTime? -
i can't find on net me figure out, if please lifesaver.
my function given property name , object. using reflection returns value of property. works if pass nullable datetime gives me null , no matter try cant work.
public static string getpropvalue(string name, object obj) { type type = obj.gettype(); system.reflection.propertyinfo info = type.getproperty(name); if (info == null) { return null; } obj = info.getvalue(obj, null); return obj.tostring(); }
in above function obj null. how read datetime?
your code fine-- prints time of day:
class program { public static string getpropvalue(string name, object obj) { type type = obj.gettype(); system.reflection.propertyinfo info = type.getproperty(name); if (info == null) { return null; } obj = info.getvalue(obj, null); return obj.tostring(); } static void main(string[] args) { var dt = getpropvalue("dtprop", new { dtprop = (datetime?) datetime.now}); console.writeline(dt); } }
to avoid exception null value, change last line of getpropvalue
to:
return obj == null ? "(null)" : obj.tostring();
Comments
Post a Comment