String equality with null handling

57,543

Solution 1

Unlike Java, C# strings override the == operator:

if (str1 == str2)

If you want a case-insensitive comparison:

if (string.Equals(str1, str2, StringComparison.OrdinalIgnoreCase))

Solution 2

If you do not want to treat two null strings as equal to each other, your code is optimal.

If, on the other hand, you want to treat null values as equal to each other, you can use

object.Equals(str1, str2)

for a more "symmetric" approach that also handles null values.

This is not the only approach to a symmetric check of string equality that treats null strings as equal: you could also use string.Equals(str1, str2) or even str1 == str2, which redirects to string.Equals.

Solution 3

I know this is some years old and I think the solution from dasblinkenlight is functionally perfect for what you asked for. However I do prefer this code for readability reasons:

String.Equals(str1, str2)

Solution 4

There is no built in way to do this, but you could create an extension method to encapsulate this.

public static StringExtensions
{
    public static Boolean IsNotNullAndEquals(this string str1, string str2)
    {
        return !string.IsNullOrEmpty(str1) && str1.Equals(str2)
    }
}

then use it like this:

str1.IsNotNullAndEquals(str2);

Naming is going to be your hardest thing here IMO...since you need to convey that you are only null checking str1. When used as an extension method, it reads fairly well, but if used as a regular static, then it doesn't convey that as well.

Solution 5

This will do it:

string.IsNullOrWhiteSpace(str1) ? string.IsNullOrWhiteSpace(str2) : str1.Equals(str2, StringComparison.OrdinalIgnoreCase);
Share:
57,543
Brady Moritz
Author by

Brady Moritz

Serial entrepreneur, current ventures being Setiri Group, Deadlywind Paintball, and several others. Typically work with .Net MVC technology to build large content web apps such as Bank of America Locations app and many others. Contact me if you like via brady dot moritz at gee mail dot com

Updated on December 24, 2021

Comments

  • Brady Moritz
    Brady Moritz over 2 years

    I will often use this code to compare a string:

    if(!string.IsNullOrEmpty(str1) && str1.Equals(str2)){
        //they are equal, do my thing
    }
    

    This handles the null case first etc.

    Is there a cleaner way to do string comparison, perhaps with a single method call that will handle possible null values? I simply want to know that the strings are not equal if the testing value is null.

    (I'm having dejavu that I may have asked this before, I apologize if so)


    Update: In my case, the str2 is a known good string to compare to, so I don't need to check it for null. str1 is the "unknown" string which may be null, so I want to say "str1 does not equal str2" in the cases where str1 is null...

  • Justin Pihony
    Justin Pihony about 11 years
    I will leave it to the OP, but I believe that the goal is to also fail if either side is null
  • p.s.w.g
    p.s.w.g about 11 years
    @JustinPihony str1 == str2 && str1 != null is still a lot more elegant.
  • Justin Pihony
    Justin Pihony about 11 years
    @p.s.w.g And, that is fine, but this answer does not say that. Also, see my answer for a way to encapsulate this...as stated, the naming of the method might be hardest
  • Brady Moritz
    Brady Moritz about 11 years
    This is what I figured would be needed. Was really more curious if there is something built-in that would handle this, but is looking like a "no". Thanks!
  • Brady Moritz
    Brady Moritz about 11 years
    actually, would an extension method work for str1 if str1 is a null? I'm thinking it will bomb with a null exception
  • Justin Pihony
    Justin Pihony about 11 years
    @boomhauer First, I believe so, but will verify shortly. Second, if this works, an upvote and accept are appreciated
  • Justin Pihony
    Justin Pihony about 11 years
    @boomhauer I did not test it, but had more time to remember this. This will work even if str1 is null. The reason is because this is just syntactic sugar for calling StringExtensions.IsNotNullAndEquals(str1, str2) It only LOOKS like it is a method call on str1
  • Brady Moritz
    Brady Moritz about 11 years
    ok, this will actually work for me as str2 is a known value and not null. Thus null comparison won't matter.
  • CigarDoug
    CigarDoug about 9 years
    This is useful functionality to know. However, it doesn't help in my particular case, as an empty value in the first object is null, while an empty value in the second value is an empty string. But thanks!
  • Sergey Kalinichenko
    Sergey Kalinichenko about 9 years
    @CigarDoug With C# strings there is no such thing as "an empty value" that is "null". Unfortunately, they often do look the same, causing a lot of confusion. You can fix this by using object.Equals(str1 ?? "", str2 ?? "") expression.
  • CigarDoug
    CigarDoug about 9 years
    @dasblinkenlight In my particular case, I am comparing the current value of a SharePoint control (null if empty) to the current value of the field in the SharePoint list (empty string if empty, based on the method I use to get the value). So in this one case, I need to check for null and then check for equality. But I will look at your example to see if it accomplishes the same thing. Thanks!
  • MarkD
    MarkD almost 4 years
    nearly - I suspect a typo.. needs '??' (coalescing ) vs '?'. So answer could be if ( ( str1??"" ).Equals( str2 ) ). { they are equal }.
  • Brady Moritz
    Brady Moritz almost 3 years
    yep you were right. I mixed it with the other new operator for calling methods on potentially null objects
  • Brady Moritz
    Brady Moritz almost 3 years
    good answer but was actually already proposed
  • Grimm
    Grimm over 2 years
    I don't think this is correct. Try this code: string s1 = null; string s2 = null; if (s1 == s2) { Console.WriteLine("Equal."); } else { Console.WriteLine("NOT equal."); } It will print "Equal." (beware: this is only true for strings).
  • Sergey Kalinichenko
    Sergey Kalinichenko over 2 years
    @Grimm The fact that the code in your comment is correct has nothing to do with my answer also being verifiably correct. Your code is equivalent to string.Equals(str1, str2) to which operator== redirects.
  • Grimm
    Grimm over 2 years
    I had the impression that you wanted to express with your answer that only object.Equals(str1, str2) considers null values as equal, but not "==".
  • Sergey Kalinichenko
    Sergey Kalinichenko over 2 years
    @Grimm That's fair, I added a note to avoid this confusion.
  • Grimm
    Grimm over 2 years
    Excellent. I reread the opening question and sure enough, he doesn't ask for "==" at all. However, comparing with == or != is so common under C# (as opposed to the constant use of .Equals() under Java) that I missed it while reading the answer. So in terms of content I was really wrong and you are right - but this way it won't happen to the next reader as well. Thank you.