c# - Trim spaces in a object recursively using reflection -
i writing extension method trimspaces on object recursively should able trim spaces. successful in trimming spaces first level object, however, unable same child objects.
as example, consider following class
public class employee { public string employeeid { get; set; } public string employeename { get; set; } public datetime hiredate { get; set; } public department employeedepartment { get; set; } } public class department { public int departmentid { get; set; } public string departmentname { get; set; } }
in above class able trim spaces employee class properties unable trim departmentname
here code have written
public static t trimspaces<t>(this t obj) { var properties = obj.gettype() .getproperties(bindingflags.instance | bindingflags.public) .where(prop => prop.propertytype == typeof(string)) .where(prop => prop.canwrite && prop.canread); foreach (var property in properties) { var value = (string)property.getvalue(obj, null); if (value.hasvalue()) { var newvalue = (object)value.trim(); property.setvalue(obj, newvalue, null); } } var customtypes = obj.gettype() .getproperties(bindingflags.instance | bindingflags.public) .where( prop => !prop.gettype().isprimitive && prop.gettype().isclass && !prop.propertytype.fullname.startswith("system")); foreach (var customtype in customtypes) { ((object)customtype.getvalue(obj).gettype()).trimspaces(); } return obj; }
when loop through properties, invoking line:
((object)customtype.getvalue(obj).gettype()).trimspaces();
which invokes trimspaces
passing type of object obj
. instead should pass object self this:
((object)customtype.getvalue(obj)).trimspaces();
in case, cast object
not needed, can have this:
customtype.getvalue(obj).trimspaces();
Comments
Post a Comment