简体   繁体   中英

How to set default values to string if it is null or empty

Is there Better way to check if a string is empty or null using Null Coalescing operator.When I use empty value to a string instead of null the null Coalescing operator failed to get me the desired result.

 string x = null;
 string y = x ?? "Default Value";
 Console.WriteLine(y);
    

Here if I replace x = null with x="" this doesnt work.

If I use String.IsNullOrEmpty method

if(String.IsNullOrEmpty(x)
{
    y= "default value"
}
{
    y =x 
}
    

My code block is having multiple lines and I want to make it simple. Can you suggest a better way to keep the code clean and simple. As it is used in many places.

You can use the ? operator

string x = null;
string y = string.IsNullOrEmpty(x) ? "Default Value" : x;
Console.WriteLine(y);

Given that you say "it is used in many places" then it might be appropriate to write an extension method to help with this:

public static class StringExt
{
    public static string OrIfEmpty(this string? self, string defaultValue)
    {
        return !string.IsNullOrEmpty(self) ? self : defaultValue;
    }
}

Which you would use like so:

string? x = null;

string y = x.OrIfEmpty("test");

Console.WriteLine(y); // "test"

You could probably choose a better name for OrIfEmpty() depending on taste.

However, note that this suffers from the drawback that the default value is always evaluated. If obtaining the default is expensive, then using this extension method will hurt performance because the default will always be evaluated even if it's not used.

To circumvent that issue you'd add an extension method to allow you to pass a Func<string> instead:

public static string OrIfEmpty(this string? self, Func<string> defaultValue)
{
    return !string.IsNullOrEmpty(self) ? self : defaultValue();
}

Then when calling it you'd have to pass a delegate for the default, eg:

public sealed class Program
{
    public static void Main()
    {
        string? x = null;

        string y = x.OrIfEmpty(expensiveDefault);
        
        Console.WriteLine(y);
    }

    static string expensiveDefault()
    {
        return "test";
    }
}

I'm just posting this for consideration. Myself, I would just use Marco's answer. But if you have a LOT of code that does it, then just maybe...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM