Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String equality with null handling

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

like image 658
Brady Moritz Avatar asked Mar 03 '13 16:03

Brady Moritz


People also ask

Can you use == with null?

The comparison and not equal to operators are allowed with null in Java. This can made useful in checking of null with objects in java.

Why == is not working for strings?

You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.

How do you write a string that is not equal to null in Java?

For any non-null reference value x , x. equals(null) should return false . The way to compare with null is to use x == null and x !=


2 Answers

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

if (str1 == str2) 

If you want a case-insensitive comparison:

if (string.Equals(str1, str2, StringComparison.OrdinalIgnoreCase)) 
like image 131
SLaks Avatar answered Oct 08 '22 06:10

SLaks


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.

like image 27
Sergey Kalinichenko Avatar answered Oct 08 '22 06:10

Sergey Kalinichenko