the following function needs to look inside the input object if there is a property in it that returns a custom object it needs to do the trimming of that object as well. The code below works for the input object fine, but wont recursively look into a property that returns a custom object and do the trimming process.
public object TrimObjectValues(object instance)
{
var props = instance.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)
// Ignore non-string properties
.Where(prop => prop.PropertyType == typeof(string) | prop.PropertyType == typeof(object))
// Ignore indexers
.Where(prop => prop.GetIndexParameters().Length == 0)
// Must be both readable and writable
.Where(prop => prop.CanWrite && prop.CanRead);
foreach (PropertyInfo prop in props)
{
if (prop.PropertyType == typeof(string))
{
string value = (string)prop.GetValue(instance, null);
if (value != null)
{
value = value.Trim();
prop.SetValue(instance, value, null);
}
}
else if (prop.PropertyType == typeof(object))
{
TrimObjectValues(prop);
}
}
return instance;
}
I need to change this somehow to look for other objects inside the initial object
.Where(prop => prop.PropertyType == typeof(string) | prop.PropertyType == typeof(object))
This code isn’t working reason is for a example is the object I am passing as input has a property that returns a type of “Address” therefore typeof(object) never gets hit.
Here is a tree of data to test against pass the function “o” in this case
Order o = new Order();
o.OrderUniqueIdentifier = "TYBDEU83e4e4Ywow";
o.VendorName = "Kwhatever";
o.SoldToCustomerID = "Abc98971";
o.OrderType = OrderType.OnOrBefore;
o.CustomerPurchaseOrderNumber = "MOOMOO 56384";
o.EmailAddress = "abc@electric.com";
o.DeliveryDate = DateTime.Now.AddDays(35);
Address address1 = new Address();
//address1.AddressID = "Z0mmn01034";
address1.AddressID = "E0000bbb6 ";
address1.OrganizationName = " Nicks Organization ";
address1.AddressLine1 = " 143 E. WASHINGTON STREET ";
address1.City = " Rock ";
address1.State = "MA ";
address1.ZipCode = " 61114";
address1.Country = "US ";
o.ShipToAddress = address1;
Your tests with
typeof(object)will all fail.Try like this:
I have also made the function return no value because you are modifying the argument instance anyway.
Test case:
UPDATE 2:
It seems that you want to handle also lists of objects. You could adapt the method: