Just for curiosity/convenience: C# provides two cool conditional expression features I know of:
string trimmed = (input == null) ? null : input.Trim();
There's nothing built-in, but you could wrap it all up in an extension method if you wanted (although I probably wouldn't bother).
For this specific example:
string trimmed = input.NullSafeTrim();
// ...
public static class StringExtensions
{
public static string NullSafeTrim(this string source)
{
if (source == null)
return source; // or return an empty string if you prefer
return source.Trim();
}
}
Or a more general-purpose version:
string trimmed = input.IfNotNull(s => s.Trim());
// ...
public static class YourExtensions
{
public static TResult IfNotNull(
this TSource source, Func func)
{
if (func == null)
throw new ArgumentNullException("func");
if (source == null)
return source;
return func(source);
}
}