I am writing an extension method TrimSpaces on a object so that it recursively should be able to trim spaces. I was successful in trimming the spaces for the first level object, however, I am unable to do the same for the child objects.
As an example, consider the 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 the above class I am currently able to trim spaces from Employee class properties but I am unable to trim the DepartmentName
Here is the code that I 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;
}