Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using == or .Equals() on nulls and string.Empty

Tags:

string

c#

null

In reference to using .Equals() or == on strings, here is a question in regards to checking for string.Empty and null objects.

In comparing string.Empty and null objects, should I use == or should I use .Equals()?

// Add vars to instance variables
for (int i = 0; i < paramFirstList.Count; i++)
{
    // if the key is null, replace it
    // with a "null" string
    if (paramFirstList[i] == null)
    {
        _firstList.Add("null");
    }
    else if (paramFirstList[i] == string.Empty)
    {
        _firstList.Add("empty");
    }
    else
    {
        // Do something
    }
}

P.S. I understand it's better to store null and string.Empty as their object types, but for this particular purpose, it is in my requirements to store them as a string representation :).

P.P.S. Added hungarian notation for the sake of question clarity

like image 750
theGreenCabbage Avatar asked Sep 10 '25 04:09

theGreenCabbage


1 Answers

You should always favor == over Equals. The latter is a method of the base Object type which in this case will do useless casting.

If you mean to check whether a string value is null or empty, use String.IsNullOrEmpty method. If, instead, you need to act differently if it's one or the other, then do this:

if (value == null)
{
    //do stuff
}
else if (value == string.Empty)
{
    // do other stuff
}

EDIT:

As pointed out in the comments there is an overloaded Equals method on a string that receives a string parameter. Still, I think you should take the habit of using ==. It just reads better IMHO.

like image 159
Crono Avatar answered Sep 12 '25 18:09

Crono