String.IsNullOrEmpty()
appears to be an extremely well used method and I find myself wishing there were some shorthand for it. Something like ???
as it would be used in a similar context to the null coalesce operator but be extended to test for empty as well as null strings. I.e.
string text = something.SomeText ??? "Not provided";
What would be your opinions on this? Would it unnecessarily bloat the language? Would it open the floodgates for other mid-level operations to be granted such deep integration with the compiler? Or would it be a useful addition for the language.
In C#, IsNullOrEmpty() is a string method. It is used to check whether the specified string is null or an Empty string. A string will be null if it has not been assigned a value. A string will be empty if it is assigned “” or String. Empty (A constant for empty strings).
The C# IsNullOrEmpty() method is used to check whether the specified string is null or an Empty string. It returns a boolean value either true or false.
The IsNullOrEmpty() method returns true if the input is null . IsNullOrEmpty() returns true if the input is an empty string. In C#, this is a zero length string ("").
IsNullOrEmpty vs IsNullOrWhiteSpace The main difference between IsNullOrEmpty and IsNullOrWhiteSpace in C# is that IsNullOrEmpty checks if there's at least one character, while IsNullOrWhiteSpace checks every character until it finds a non-white-space character.
Phil Haack blogged about this a while ago. Basically, he suggests an extension method on string
that lets you 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;
}
He also suggests a version checking for whitespace instead of just empty with the string.IsNullOrWhitespace()
method from .NET 4, as well as similar extensions for the IEnumerable<T>
interface.
He also talks about introducing new operators such as ???
for this, but concludes that it would be more confusing than helpful - after all, introducing these extension methods you can do the same thing, but it's more readable, and it's using shorthand syntax that "everybody already knows".
Phil Haack talks about this exact operation on his blog. You should check out his article Null Or Empty Coalescing
.
Special purpose operators like ???
are a slippery slope. Why stop there - why not introduce a "null or empty or whitespace" operator: ????
. Phil talks about this, actually, in his article. His overall conclusion is that such operators would be more confusing than helpfull.
Ultimately you could take many different operations an invent operators to represent them - unfortunately, that would likely destroy the readability of the language.
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