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...
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.
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.
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 !=
Unlike Java, C# strings override the ==
operator:
if (str1 == str2)
If you want a case-insensitive comparison:
if (string.Equals(str1, str2, StringComparison.OrdinalIgnoreCase))
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With