Search code examples
c#null-coalescing-operator

Negate the null-coalescing operator


I have a bunch of strings I need to use .Trim() on, but they can be null. It would be much more concise if I could do something like:

string endString = startString !?? startString.Trim();

Basically return the part on the right if the part on the left is NOT null, otherwise just return the null value. I just ended up using the ternary operator, but is there anyway to use the null-coalescing operator for this purpose?


Solution

  • You could create an extension method which returns null when it tries to trim the value.

    public String TrimIfNotNull(this string item)
    {
       if(String.IsNullOrEmpty(item))
         return item;
       else
        return item.Trim();
    }
    

    Note you can't name it Trim because extension methods can't override instance methods.