Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 373
jhunter Avatar asked May 17 '10 21:05

jhunter


1 Answers

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.

like image 96
kemiller2002 Avatar answered Sep 22 '22 01:09

kemiller2002