Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
358 views
Welcome To Ask or Share your Answers For Others

1 Answer

C# already lets us substitute values for null with ??. So all we need is an extension that converts an empty string to null, and then we use it like this:

s.SiteNumber.NullIfEmpty() ?? "No Number";

Extension class:

public static class StringExtensions
{
    public static string NullIfEmpty(this string s)
    {
        return string.IsNullOrEmpty(s) ? null : s;
    }
    public static string NullIfWhiteSpace(this string s)
    {
        return string.IsNullOrWhiteSpace(s) ? null : s;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...