views:

500

answers:

4

If this is a duplicate please point me to it and I'll close, I couldn't find anything. Something I find myself doing more and more is checking a string for empty (as in "" or null) and a conditional operator.

A current example:

s.SiteNumber.IsNullOrEmpty() ? "No Number" : s.SiteNumber;

This is just an extension method, it's equivalent to:

string.IsNullOrEmpty(s.SiteNumber) ? "No Number" : s.SiteNumber;

Since it's empty and not null, ?? won't do the trick. A string.IsNullOrEmpty() version of ?? would be the perfect solution. I'm thinking there has to be a cleaner way of doing this (I hope!), but I've been at a loss to find it.

Does anyone know of a better way to do this, even if it's only in .Net 4.0?

+10  A: 

There isn't a built-in way to do this. You could make your extension method return a string or null, however, which would allow the coalescing operator to work. This would be odd, however, and I personally prefer your current approach.

Since you're already using an extension method, why not just make one that returns the value or a default:

string result = s.SiteNumber.ConvertNullOrEmptyTo("No Number");
Reed Copsey
I think you're right, and this is the cleanest solution currently available that's still readable. I'd love something like a `???` operator in C# 5 though, who knows.
Nick Craver
+7  A: 

You could change your extension to return null if SiteNumber is empty:

s.SiteNumber.NullIfEmpty() ?? "No Number";
RedFilter
?? without : would be sufficient. guess that's a typo?
devio
Typo, thanks :)
RedFilter
A: 

how about a string extension method ValueOrDefault()

public static string ValueOrDefault(this string s, string sDefault)
{
    if (string.IsNullOrEmpty(s))
        return sDefault;
    return s;
}

or return null if string is Empty:

public static string Value(this string s)
{
    if (string.IsNullOrEmpty(s))
        return null;
    return s;
}

Didn't try these solutions though.

devio
A: 

I came up with this the other day:

public static string operator ‽‽(string s1, string s2)
{
    return string.IsNullOrEmpty(s1) ? s2 : s1;
}

public static string operator ‽(string s1)
{
    return string.IsNullOrEmpty(s1);
}

/*
Usage:
"" ‽‽ "two" == "two"
‽"" == true
*/

I used a unicode character just for fun, but I couldn't think of anything else appropriate.

travis
C# does not support this.
SLaks
it doesn't support operator overload or unicode operators? http://msdn.microsoft.com/en-us/library/aa288467%28VS.71%29.aspx
travis