views:

179

answers:

7

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?

+3  A: 
string endString = string.IsNullOrEmpty(startString) ? startString : startString.Trim();

Though I've also gone the route of writing a string extension method called "safeTrim" which does what you're describing in one method instead of having to use this recipe every time. Check out Kevin's respone for the code.

EDIT: wow I had it all kinds of backwards, wrongly named variables and reversed ternary operators, all the more reason to write one extension method and code check it better than I did!

Daniel DiPaolo
Ninja-edited thanks to Frank's comment reminding me that it's `string.IsNullOrEmpty(foo)` and not `foo.IsNullOrEmpty()`
Daniel DiPaolo
Checks for empty. Not what he is asking for
Alfred Myers
Ah, yes. At first I thought "the empty check is an effective no-op" because the normal use case is to just return `endString` at the end instead of `null`, but I had explicitly put `null` at the end. Changed to the normal use case and it makes the null check effectively a no-op.
Daniel DiPaolo
Also, this will throw a `NullReferenceException` if `startString == null`. You might want to switch the ordering of the expressions ;)
Jørn Schou-Rode
Excellent, didn't even think of an extension method. Thanks.
jhunter
And how can `endString` be in scope already when it is defined within this particular statement? I think you need to do some more ninja editing...
Jørn Schou-Rode
I think you mean `string endString = string.IsNullOrEmpty(startString) ? startString : startString.Trim();`. He wants the null string if it is null/empty, and he wants to trim it if it is _not_ null/empty.
Sarah Vessels
I don't think he mentioned Null **or Empty**, just null.
sixlettervariables
@Sarah indeed I did, I had it very much backwards and even chose the wrong variable name for one branch anyway, wow *headdesk*
Daniel DiPaolo
+2  A: 

Use

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

This uses an empy string if startString is null. This, however, does not return null when endString is null.

Obalix
If startString is null he want endString to be null. Your sample will return string.Empty
Alfred Myers
It is stated in the post ...
Obalix
+7  A: 

Not to spec: Not that I like it, but you could use:

string endString = (startString ?? String.Empty).Trim();

To spec, better as an Extension method like @Kevin's:

string endString = (startString == null ? null : startString.Trim());
sixlettervariables
Genius. Thanks!
Bryan Ross
Does not propagate null as he asked for
Alfred Myers
this doesn't return null if startString is null.
Serge - appTranslator
Took me a second read to realize he actually wanted the null... @Kevin has the right idea in that case.
sixlettervariables
Why not use `string.IsNullOrEmpty()`?
Sarah Vessels
He wants null's to stay null's and empty to stay empty, I gathered.
sixlettervariables
+10  A: 

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.

Kevin
It feels so wrong that this works when `item` is null... But, I did confirm it works. `string s = null; s.TrimIfNotNull();` No `NullReferenceException` like you'd get with a regular instance method (even one that doesn't reference to any members).
Nathan Ernst
It makes perfect sense why it works. Extension methods are nothing more than static methods which are appended to an object. Really there is no reason why they shouldn't work. The class can't depend on anything they do since they weren't created when the original class was, and they can't access any of the private methods or object. It would be hindering to not allow the to be used on a null object (although I do admit it is a little odd at first).
Kevin
Yes, the climax of that feature is the IfNotNull extension method : `public V IfNotNull<T, V>(this T @in, Func<T,V> access)`
flq
A: 

The following doesn't propagate null but it accepts null as a parameter and returns an empty string in that case.

using Microsoft.VisualBasic;  // you need to add a reference to Microsoft.VisualBasic.dll

    ...
    string endString = Strings.Trim(startString);
    ...

duck&run...

Heinzi
A: 

Create a method such as:

string MyTrim(string a) {
    if (a != null) {
        a = a.Trim();
    }
    return a;
}
Alfred Myers
A: 

As as side note, if you're using .NET 4, there's a new convenient method String.IsNullOrWhiteSpace which you can use.

hmemcpy
Interesting method, but seems orthogonal to the problem the OP has.
Brian
Yeah, sorry, I misread the question...
hmemcpy