How to check if String is 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))
{
...
}

Tags:

C#

Null