开发者

Handling empty strings in C# ?? operator

I am using the following code:

string x = str1 ?? str2 ?? str3 ??  "No string";

However what if any of these strings (str1, str2, str3) is String.Empty which is !=null?

How do I handle 开发者_StackOverflow社区this situation?


You can't with ??. You could do something like this, using Linq:

string x = new[]{ str1, str2, str3, "No string" }.First(x => !string.IsNullOrEmpty(x));


i would write a helper method:

    public static string Coalesce(string defaultValue, params string[] values) {
        if (string.IsNullOrEmpty(defaultValue))
            throw new ArgumentException("defaultValue");

        foreach (var value in values) {
            if (!string.IsNullOrEmpty(value))
                return value;
        }
        return defaultValue;
    }

usage:

var data = StringHelpers.Coalesce("No text", s1, s2, s3, s4);

This is not particularly useful, but you can even create an extension method (appending "this" in front of first parameter), maybe change to a more "fluent" name, and write something like:

var data = "No Text".IfEmptyOrNull(s1, s2, s3);


You can use String.IsNullOrEmpty().

E.g.

String.IsNullOrEmpty(null)            => true
String.IsNullOrEmpty("")              => true
String.IsNullOrEmpty("hello, world!") => false
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜