Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if String is null

Tags:

c#

null

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?

like image 558
Otiel Avatar asked Sep 26 '11 10:09

Otiel


People also ask

How do you check if a string is empty or null?

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.

How do you check if a string is null or not in C#?

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.

How do you check if a string is not null or empty in Java?

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.


2 Answers

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.

like image 92
Jon Skeet Avatar answered Oct 08 '22 11:10

Jon Skeet


To be sure, you should use a function to check for null and empty as below:

string str = ... if (!String.IsNullOrEmpty(str)) { ... } 
like image 20
MrTo-Kane Avatar answered Oct 08 '22 12:10

MrTo-Kane