Well, it's easy enough to get all the properties, and find out which ones are strings and writable. LINQ makes it even easier.
var props = instance.GetType()
.GetPropertes(BindingFlags.Instance |
BindingFlags.Public)
// Ignore non-string properties
.Where(prop => prop.PropertyType == typeof(string))
// 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)
{
string value = (string) prop.GetValue(instance, null);
if (value != null)
{
value = value.Trim();
prop.SetValue(instance, value, null);
}
}
You may want to only set the property if trimming actually makes a difference, to avoid redundant computations for complex properties - or it may not be an issue for you.
There are various ways of improving the performance if necessary - things like:
- Simply caching the relevant properties for each type
- Using
Delegate.CreateDelegate
to build delegates for the getters and setters
- Possibly using expression trees, although I'm not sure whether they'd help here
I wouldn't take any of those steps unless performance is actually a problem though.