I am wondering if there is a special method/trick to check if a String
object is null. I know about the String.IsNullOrEmpty
method but I want to differentiate a null
String from an empty String (=""
).
Should I simply use:
if (s == null) { // blah blah... }
...or is there another way?
Using the isEmpty() Method The isEmpty() method returns true or false depending on whether or not our string contains any text. It's easily chainable with a string == null check, and can even differentiate between blank and empty strings: String string = "Hello there"; if (string == null || string.
C# | IsNullOrEmpty() Method 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.
StringUtils. isEmpty(String str) - Checks if a String is empty ("") or null. StringUtils. isBlank(String str) - Checks if a String is whitespace, empty ("") or null.
An object can't be null - the value of an expression can be null. It's worth making the difference clear in your mind. The value of s
isn't an object - it's a reference, which is either null or refers to an object.
And yes, you should just use
if (s == null)
Note that this will still use the overloaded == operator defined in string, but that will do the right thing.
To be sure, you should use a function to check for null and empty as below:
string str = ... if (!String.IsNullOrEmpty(str)) { ... }
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