Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a NullOrEmpty coalescing operator

Tags:

c#

Would it be possible to add a new operator to the String class that looked something like

string val = anotherVal ??? "Default Val";

and worked like

string val = !String.IsNullOrEmpty(anotherVal) ? anotherVal : "Default Val";
like image 544
JeremyWeir Avatar asked Nov 04 '25 09:11

JeremyWeir


1 Answers

You can't define your own operators for the string class and use them from C#. (F# allows you to create operators for arbitrary classes, a bit like extension methods but for other member types.)

What you can do is write an extension method:

public static string DefaultIfEmpty(this string original, string defaultValue)
{
    return string.IsNullOrEmpty(original) ? defaultValue : original;
}

And call it with:

string val = anotherValue.DefaultIfEmpty("Default Val");

If you don't want to evaluate the "default" string unless it's needed, you could have an overload taking a function:

public static string DefaultIfEmpty(this string original,
                                    Func<string> defaultValueProvider)
{
    return string.IsNullOrEmpty(original) ? defaultValueProvider() : original;
}

And call it with:

string val = anotherValue.DefaultIfEmpty(() => "Default Val");
like image 156
Jon Skeet Avatar answered Nov 06 '25 01:11

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!