I’m beginner in C# and today I met with interesting thing as when I tryed compare empty string property by string.Empty.
Why is this code in a condition returns false, if it is literally empty?
private string _id;
public string Id
{
get => _id;
set
{
if (value != string.Empty)
_id = value;
}
}
// ... code ...
// this condition returns false
if(Id == string.Empty)
{
// any code is here
}
Just replaced string.Empty by "null" and it works nicely.
I guess that string wasn’t initialized and become it equals null, not "".
>Solution :
here 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 (string.IsNullOrEmpty(Id))
{
// your logic here
}