4

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

theGreenCabbage
  • 5,197
  • 19
  • 79
  • 169
  • The question is not clear, first you're talking of `String.Empty` and `null` but then you are adding `"empty"` and `"null"`. Also you `P.S` is even more confusing. – Tim Schmelter Feb 26 '14 at 15:59
  • 1
    @Tim: I believe that the PS is answering your question. He is saying that rather than storing `null` he is storing `"null"` and while he knows he should store them as object types (ie `null`) he is storing them as a string representation (ie `"null"`). His checks are workign on string.empty and null though so I'm not sure why you are worrying about what he is putting in the list. – Chris Feb 26 '14 at 16:02
  • I knew someone would mention storing the string representation of `null` and/or `string.Empty` so I put the disclaimer there that I know what I am doing, and what I am doing is on purpose. – theGreenCabbage Feb 26 '14 at 16:03
  • Well, What's that `firstList` type? `List` or `List`? – Sriram Sakthivel Feb 26 '14 at 16:04
  • 1
    @SriramSakthivel: Is that relevant? the thing we are looking at is, as the title says, "Using == or .Equals() on nulls and string.Empty". What he is putting in the list and what type it is seems irrelevant to me... – Chris Feb 26 '14 at 16:06
  • Both are `List` – theGreenCabbage Feb 26 '14 at 16:06
  • @Chris Yes relevant. If it is `List` then `==` operator would fail. – Sriram Sakthivel Feb 26 '14 at 16:07
  • Ah yes, sorry. I misread you as asking about `_firstList` for some reason. – Chris Feb 26 '14 at 16:08
  • 1
    @Chris Nevermind, confusions due to poor naming conventions :p – Sriram Sakthivel Feb 26 '14 at 16:09
  • Should I change the way the names work? It seems to be confusing some people. The `_firstList` is an instance variable while `firstList` is the input for this constructor. – theGreenCabbage Feb 26 '14 at 16:12
  • Yes I suggest you better change names to avoid further confusions; not only in your question in production code too – Sriram Sakthivel Feb 26 '14 at 16:14
  • IMHO this is okay (and quite common) to prefix private class members with an underscore. It just wasn't easy to figure out in a SO question context. :) In any case, given the question it's not that much important. – Crono Feb 26 '14 at 16:14
  • What naming scheme to differentiate between an input parameter vs. an instance variable? – theGreenCabbage Feb 26 '14 at 16:25
  • For the sake of making sample code as easy to understand as possible, drop the underscore for your instance variable and just append "Param" to your parameter variable name. Of course, don't do that in production code. ;) Again, though: this is hardly an issue. The question is about using Equals or ==. – Crono Feb 26 '14 at 16:27
  • Yeah I'm not sure about using Hungarian Notation in my production code ;-). – theGreenCabbage Feb 26 '14 at 16:28
  • 1
    Keep in mind that if you try to call `s.Equals(null)` when `s` is in fact `null` you'll end up with an `NullReferenceException`. – Grx70 Feb 26 '14 at 16:39

2 Answers2

4

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.

Crono
  • 10,211
  • 6
  • 43
  • 75
  • 4
    "The latter is a method of the base Object type." Just to make it explicit, it *is* overriden (so it's a value comparision too) and there is also an overload which takes a `String` parameter. – Matthias Meid Feb 26 '14 at 16:09
  • Thanks, added an additional precision. – Crono Feb 26 '14 at 16:11
  • 1
    There is no boxing/unboxing involved in strings, because string is a reference type – Georg Feb 26 '14 at 16:26
  • I am rather still confused -- it's a better idea to use `value == string.Empty` than `value.Equals(string.Empty)`? – theGreenCabbage Feb 26 '14 at 16:28
  • @Georg you are absolutely right, I tend to forget strings are references not values. :) – Crono Feb 26 '14 at 16:31
  • @theGreenCabbage as I said: favor ==. – Crono Feb 26 '14 at 16:32
  • That's just.. so against what I learned, haha. I've always read from Stack that for string comparisons, you should use `.Equals()` versus `==`, since `==` checks object reference while `.Equals()` checks string equality. This question is to clarify that, I suppose. – theGreenCabbage Feb 26 '14 at 16:33
  • 2
    @theGreenCabbage This holds for many languages like e.g. Java, but C# knows operator overloading and indeed, == is overloaded for string. Thus, there is absolutely no difference between == and Equals in C#, besides readability and understandability – Georg Feb 26 '14 at 16:35
  • Ah thank you! You're entirely right -- http://stackoverflow.com/questions/1659097/c-string-equals-vs – theGreenCabbage Feb 26 '14 at 16:36
  • I would say there *is* a difference: with the == operator you still can compare two null strings. Equals will require that at least one instance is non null. ;) – Crono Feb 26 '14 at 16:37
  • Well -- thanks for the awesome discussion guys! Solved my issue and answered my question. Adieu. – theGreenCabbage Feb 26 '14 at 16:40
3

If you're concerned about null, you should use string.IsNullOrEmpty(), or perhaps string.IsNullOrWhitespace()

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • @Chris I had the feeling this was just sample code. – Joel Coehoorn Feb 26 '14 at 16:01
  • Surely if that is the case you should still answer the question not some other question that you think he meant? – Chris Feb 26 '14 at 16:03
  • 1
    @Chris but that is no problem either, because comparing against null is no longer necessary he could do sth like `if(string.IsNullOrEmpty(stringVar)) { if(stringVar.Equals(string.Empty)) { .....` so one could catch that case too seperately – DrCopyPaste Feb 26 '14 at 16:03
  • 1
    @DrCopyPaste: Yes, there are ways around it but the title of the question says its about using the merits of `==` vs `.Equals`. An answer that doesn't cover either of those for the uses in question is surely not even close to answering the question... – Chris Feb 26 '14 at 16:05
  • 1
    I would note that I have no problem with recommending use of this method as an additional note, I just don't believe it is a valid answer (though voting would seem to disagree with me) – Chris Feb 26 '14 at 16:07
  • 1
    Yep! Detecting separately is important. – theGreenCabbage Feb 26 '14 at 16:07