Home > Software design >  How to set default values to string if it is null or empty
How to set default values to string if it is null or empty

Time:09-08

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.

CodePudding user response:

You can use the ? operator

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

CodePudding user response:

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, e.g:

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...

  • Related