String
is a reference type, which means it can have a null reference
Eg
string myString = null;
It can also be empty, which is to say, there is a reference to it, and it has 0 character length
Eg
string myString = "";
// or
string myString = string.Empty;
And just for completeness, it can also have white space
Eg
string myString = " ";
You can check for null
like so
if(myString == null)
You can check for empty
if(myString == "")
// or
if(myString == string.Empty)
You can check for both, not null
and not empty
if(myString != null && myString != string.Empty)
You could use Null conditional Operator with Length
to check both is not null
and not empty
if(myString?.Length > 0)
Or you can use the built in string methods, to make it a little easier
String.IsNullOrEmpty(String) Method
Indicates whether the specified string is null or an empty string
("").
if(string.IsNullOrEmpty(myString))
String.IsNullOrWhiteSpace(String) Method
Indicates whether a specified string is null, empty, or consists only
of white-space characters.
if(string.IsNullOrWhiteSpace(myString))
Note : It's worth noting, that IsNullOrWhiteSpace
generally more robust when checking user input