When trying to figure out if a string is null or empty, I usually have the string already. That's why I would have expected a utility function such as String.IsNullOrEmpty() to work without parameters:
String myString;
bool test=myString.IsNullOrEmpty();
However, this does not work, because IsNullOrEmpty expects a String parameter. Instead, I have to write:
String myString;
bool test=String.IsNullOrEmpty(myString);
Why is this so? It seems unnecessarily clunky. Of course I can easily write own extension method for this, but it seems like a very obvious omission, so I am wondering if there is any good reason for this. I can't believe that the parameterless overload of this function has just been forgotten by Microsoft.
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.
No overload for method 'method' takes 'number' arguments. A call was made to a class method, but no definition of the method takes the specified number of arguments.
C# String IsNullOrEmpty() It returns a boolean value either true or false.
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.
If the String would be null
, calling IsNullOrEmpty()
would cause a NullReferenceException
.
String test = null;
test.IsNullOrEmpty(); // Instance method causes NullReferenceException
Now we have extension methods and we can implement this with an extension method and avoid the exception. But allways keep in mind that this only works because extension methods are nothing more than syntactical sugar for static methods.
public static class StringExtension
{
public static Boolean IsNullOrEmpty(this String text)
{
return String.IsNullOrEmpty(text);
}
}
With this extension method the follwing will never thrown an exception
String test = null;
test.IsNullOrEmpty(); // Extension method causes no NullReferenceException
because it is just syntactical sugar for this.
StringExtension.IsNullOrEmpty(test);
This method has been around long before extension methods were added to C#, and before extension methods, there was no way to define an instance method/property such as xyz.IsNullOrEmpty()
that you could still call if xyz
was null
.
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