In this post, we will see how to resolve String Property is null
Question:
I’m a beginner in C# and today I came across this interesting thing. When I tried to compare an empty string property bystring.Empty
.Why does this code return false, when it is literally empty?
string.Empty
with null
and it works as expected.
I guess that string wasn’t initialized and equaled null
, not “”.Best Answer:
There are two kinds of types in C#: reference types and value types. Variables of reference types store references to their data (objects), while variables of value types directly contain their data.String
is a reference type.So if you create a variable for reference type and don’t initialize it there is no value in it and there is no object and no reference to this non-existent object. Just
null
.If you compare “non-existence” with some real string object it will returns false because nothing not equals to something.
Also, if you want to check both null and empty strings in your condition, you can use
string.IsNullOrEmpty(Id)
.string.IsNullOrEmpty() Indicates whether the specified string is null or an empty string ("").
If you have better answer, please add a comment about this, thank you!
Source: Stackoverflow.com