After I submitted my last post, I realized that everyone might not be able to use that code as is because they might not have a base entity class. No worries. I've ever-so-slightly modified the code to make Trim a standalone method that accepts and returns any object:
public
static object Trim(object entity)
{
Type t = entity.GetType();
// We're only interested in trimming the public properties, so there is
// no need to set BindingFlags on the GetProperties call.
foreach (PropertyInfo pi in t.GetProperties())
{
if (pi.PropertyType == Type.GetType("System.String"))
{
object currentVal = pi.GetValue(entity, null);
pi.SetValue(entity, currentVal.ToString().Trim(), null);
}
}
return entity;
}
So assuming you have a Customer entity, you can do something like this (be sure to cast it appropriately):
return (Customer)TrimEntity(myCustomer);
Print | posted on Friday, October 14, 2005 11:07 AM