Is there a case for the String.IsNullOrEmpty statement?

String.IsNullOrEmpty() seems to be an extremely well-used method, and I find that I want it to be shortened a bit. Something like ??? since it will be used in a similar context with the null coalesce operator, but will be extended to check for both empty and null strings. I.e.

  string text = something.SomeText ??? "Not provided"; 

What would be your opinion on this? Will it unnecessarily inflate the tongue? Will gateways open such deep integration with the compiler for other mid-level operations? Or it will be a useful addition to the language.

+6
c #
source share
2 answers

Phil Haack wrote about this a while ago. Basically, it offers an extension method to string that allows you to do

 var text = someString.AsNullIfEmpty() ?? "Not provided."; 

The extension method is very simple:

 public static string AsNullIfEmpty(this string str) { return !string.IsNullOrEmpty(str) ? str : null; } 

It also offers version checking for spaces instead of empty using the string.IsNullOrWhitespace() method from .NET 4, as well as similar extensions for the IEnumerable<T> interface.

He also talks about introducing new operators for this, such as ??? but concludes that this will be more confusing than useful. In the end, by introducing these extension methods, you can do the same, but it is more readable, and this is using a shorthand syntax that "everyone already knows."

+15
source share

Phil Haack talks about this exact operation on his blog. You should check out his Null Or Empty Coalescing .

Special operators like ??? - This is a slippery slope. Why stop - why not enter the operator "empty or empty or white space": ???? . Phil talks about this, in fact, in his article. His general conclusion is that such operators will be more confusing than useful.

Ultimately, you could accept the many different operations that inventor-operators present for them — unfortunately, this will likely lead to a loss of readability of the language.

+6
source share

All Articles