views:

357

answers:

10

I've got a one line method that resolves a null string to string.Empty which I thought might be useful as an extension method - but I can't find a useful way of making it so.

The only way I could see it being useful is as a static method on the string class because obviously it can't be attributed to an instance as the instance is null and this causes a compiler error. [Edit: Compiler error was due to uninitialized variable, which I misinterpreted]

I thought about adding it to a helper class but that just adds unnecessary complexity from a discoverability standpoint.

So this question is in two parts I suppose:

  1. Does the .NET framework have a built in way of resolving a null string to string.Empty that is common knowledge that I have missed somewhere along the way?
  2. If it doesn't - does anyone know of a way to add this method as a static extension of the string class?

Cheers in advance

Edit:

Okay, I guess I should've been a little more clear - I'm already well aware of null coallescing and I was using this in a place where I've got a dozen or so strings being inspected for calculation of a hash code.

As you can imagine, 12 lines of code closely following each other all containing the null coallescing syntax is an eyesore, so I moved the null coallescing operation out to a method to make things easier easier on the eyes. Which is perfect, however, it would be a perfect extension to the string object:

int hashcode =
FirstValue.ResolveNull().GetHashCode() ^
SecondValue.ResolveNull().GetHashCode() ^
...

over a dozen lines is a lot easier to read than:

int hashcode =
(FirstValue ?? String.Empty).GetHashCode() ^
(SecondValue ?? String.Empty).GetHashCode() ^
...

I was running into compiler problems when I didn't explicitly declare my string values as null but relied on the implicit:

 string s;

If however, you explicitly define:

string s = null;

You can quite easily call:

s.ResolveNull();

Thanks all for your input.

A: 

Just add string.Empty to any string variable and you'll be guaranteed to never get null

string a = null;
string b = null + string.Empty;
string c = "a" + string.Empty;

(a == string.Empty).Dump(); // False
(b == string.Empty).Dump(); // True
(c == "a").Dump(); // True

I threw this in LinqPad, hence the .Dump()'s

Looking at your options...

This technique

string b = null + string.Empty;

generates

IL_0001:  ldsfld      System.String.Empty
IL_0006:  dup         
IL_0007:  brtrue.s    IL_000F
IL_0009:  pop         
IL_000A:  ldstr       ""
IL_000F:  stloc.0

The other popular option:

string b = null ?? string.empty

generates

IL_0001:  ldsfld      System.String.Empty
IL_0006:  stloc.0

and this

string b = null + "";

generates this

IL_0001:  ldstr       ""
IL_0006:  stloc.0

I still favor

string b = null + "";

But really, IMO, you should just be prepared to handle null when you digest the string

Allen
wow, really, a down vote?
Allen
+24  A: 

I don't think there's anything built in for this. My first thought, and what I do often, is use the coalesce operator:

string s = null;
string x = s ?? string.Empty;
Matt Kellogg
Idk why anyone would do this when they can just add string.Empty
Allen
@Allen - semantically, this makes it perfectly clear that the user wants an empty string instead of null. If you're adding empty strings to what appears to be an existing string, someone may misinterpret what exactly that code is supposed to be doing
John Rasch
*shrugs* I showed the IL in my post and they are the same so its up to style, IMO, my solution reads clearer but thats subjective
Allen
Looks ugly as hell if you've got many lines all needing to be resolved though, which is why I wanted to put it into an extension method.
BenAlabaster
You can write it as `(s ?? "")` as well, which is likely to be shorter than any extension method :)
Pavel Minaev
Being short and being readable aren't necessarily the same thing. When you've got a dozen lines all on top of each other that are full of symbols, like question marks, quote marks and parenthesis it's easy to start looking ugly fast.
BenAlabaster
+6  A: 

The only way I could see it being useful is as a static method on the string class because obviously it can't be attributed to an instance as the instance is null and this would cause a runtime error.

C# 3.0 extension methods can be called on null receivers (since they are static in practice), but behave as instance methods. So just make it an extension method.

Pavel Minaev
Your point on being able to call extension methods on null is 100% correct (+1) - but it will usually be more effort than null-coalescing.
Marc Gravell
Okay, I didn't see that coming - you're right. I'd not actually assigned null to my string, it was just defaulting to null after instantiation so I was getting a compiler error. When I actually declared string s = null; it fixed the issue - even though the value was still null... odd
BenAlabaster
I agree, Marc - which is why I actually voted for the first answer that mentioned `??` (Matt's). This was just to point out the incorrect statement in the question.
Pavel Minaev
Ben, local variables don't "default to null". They "default" to being uninitialized, and therefore the compiler will complain when you try to do anything with such a variable short of assigning a value it (or passing it as an `out` parameter, letting someone else do that). This has absolutely nothing to do with `null`. Try it with `int` or any other value type (which cannot be `null`) and see how it works there.
Pavel Minaev
Don't need to resolve null on those as they've got default values int is 0 for instance - I was only having the problem with my string values.
BenAlabaster
Local variables _do not have default_ values. Local ints _do not_ default to 0. Try `int x; Console.WriteLine(x);` and see. I assume you're talking about locals here because you mentioned that you mentioned earlier that you were "getting a compiler error" - there's no way you can get a compiler error about `null`, but you can and will get one for uninitialized locals.
Pavel Minaev
@Pavel: okay, I need more sleep - I just had to read that 3 times before it made sense, lol - yes, you're right. My test code is using locals, my application code is using fields - hence the discrepancy.
BenAlabaster
+4  A: 

someExpressionInvolving(s ?? "");

There is no point getting excited about string.Empty vs "" - there is negligible difference:

Console.WriteLine(ReferenceEquals(string.Empty, "")); // true
Marc Gravell
My static method uses a null coallescing - I was just trying to make things more readable as I have a dozen lines checking different fields and it looks ugly as sin.
BenAlabaster
+3  A: 

Extension method:

public static class StringExtensions
{
    public static String EmptyIfNull(this String instance)
    {
        return instance ?? String.Empty;
    }
}

of course, you can just as easily write instance ?? String.Empty in places where you need to use String.Empty instead of null.

Lasse V. Karlsen
I was using it in place where I'm calculating a hashcode, alas I have a dozen string fields that could be null and it looks ugly as all hell. I thought it would look prettier as a static extension method on string - i.e. string.ResolveNull(stringValue).GetHashCode()
BenAlabaster
+1  A: 
string test = CouldReturnNull() ?? string.Empty;
280Z28
A: 

I would say that implementing this as an extension method would feel a bit like what we in Sweden call "to travel to the other side of the creek to fetch water". When I need to ensure I get an empty string instead of null I often just concatenate with string.Empty:

public void SomeMethod(string param)
{
    string notNull = param + string.Empty;
}

Sure, this may lead to an extra string instance being created, but in most real-world situations I have been in this has not been a problem.

Fredrik Mörk
+1  A: 

You can use the ?? Operator (null-coalescing operator) in C# - is that what you mean? Or have I misunderstood?

eg.

string n = null;
string y = n ?? String.Empty;

y would = String.Empty;

Dan Diplo
+1  A: 
string abc = s ?? string.Empty;
Developer Art
A: 

There is no build in function for that. But you can write a little extension method (or a static menthod) for the string type with a statement like:

return s ?? string.Emtpy;

Alexander
its a bit much work, because he's talking about assigning, not inspecting. But typically yeah I try to use that
Allen