UPDATE: The Extension Method approach, while functional isn't great from a readability perspective. Intuitively, calling foo.NullSafeTrim();
where foo = null
will throw a NullReferenceException
. However, due to the way it is implemented it doesn't. Meh.
I agree that adding .Trim()
to every getter and setter would be laborious. Especially when you have to deal with all of the null checking to avoid NullReferenceException
s. Another option, which would make the code a bit more compact is to use Extension Methods. For instance:
public static class MyExtensions
{
public static string NullSafeTrim(this string value)
{
if (value != null)
{
value = value.Trim();
}
return value;
}
}
Then you could use the following pattern:
private string _surname;
public string Surname
{
get { return _surname.NullSafeTrim(); }
set { _surname = value.NullSafeTrim(); }
}
There are some considerations in using extension methods, which you should be able to turn up with a search on SO.
Alternatively, you could do all of the trimming and null checking in whichever class is processing the values.