How to write a collaboration operator NullOrEmpty

Is it possible to add a new operator to the String class, which would look like

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

and worked like

string val = !String.IsNullOrEmpty(anotherVal) ? anotherVal : "Default Val";
+3
source share
1 answer

You cannot define your own operators for a string class and use them from C #. (F # allows you to create statements for arbitrary classes, a bit like extension methods, but for other types of members.)

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 name it with:

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

If you do not want to evaluate the default string, if it is not required, you can get the overload using the function:

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

And name it with:

string val = anotherValue.DefaultIfEmpty(() => "Default Val");
+8
source

Source: https://habr.com/ru/post/1709243/


All Articles