?? Coalesce for empty string?

后端 未结 10 1183
甜味超标
甜味超标 2020-12-12 18:30

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:



        
10条回答
  •  抹茶落季
    2020-12-12 19:03

    I'm using a string Coalesce extension method of my own. Since those here are using LINQ, and absolutelly wasting resources for time intensive operations (I'm using it in tight loops), I'll share mine:

    public static class StringCoalesceExtension
    {
        public static string Coalesce(this string s1, string s2)
        {
            return string.IsNullOrWhiteSpace(s1) ? s2 : s1;
        }
    }
    

    I think it is quite simple, and you don't even need to bother with null string values. Use it like this:

    string s1 = null;
    string s2 = "";
    string s3 = "loudenvier";
    string s = s1.Coalesce(s2.Coalesce(s3));
    Assert.AreEqual("loudenvier", s);
    

    I use it a lot. One of those "utility" functions you can't live without after first using it :-)

提交回复
热议问题