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";
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With