Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

String Property is null

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 "".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading