Using == or .Equals () for zeros and string.Empty

Regarding use .Equals()or ==in strings, the question arises here about checking objects string.Emptyand null.

When comparing objects string.Emptyand nullshould use ==or 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
    }
}

PS I understand that it is better to store nulland string.Emptyhow to object types, but for this specific purpose in my requirements to keep them as the string representation :).

PPS Added Hungarian notation for the sake of clarity.

+3
source share
2 answers

== over Equals. Object, .

, string null , String.IsNullOrEmpty. -, , :

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

EDIT:

, Equals string, string. , , ==. .

+4

All Articles