Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Compare where null and empty are equal

Tags:

c#

Using C# and .NET 3.5, what's the best way to handle this situation. I have hundreds of fields to compare from various sources (mostly strings). Sometimes the source returns the string field as null and sometimes as empty. And of course, sometimes there is text in the fields. My current comparison of strA != strB isn't cutting it because strA is null and strB is "", for example. I know I could do the string.IsNullOrEmpty which results in a double comparison and some ugliness. Is there a better way to handle this? I thought extension methods, but you can't extend operators.

I guess I'm looking for a sexy way to do this.

like image 965
billb Avatar asked Nov 25 '09 14:11

billb


People also ask

Is null equal to empty string?

The Java programming language distinguishes between null and empty strings. An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters.

Is empty string and null same in C#?

They are not the same thing and should be used in different ways. null should be used to indicate the absence of data, string. Empty (or "" ) to indicate the presence of data, in fact some empty text.

How do you compare if strings are equal?

The equals() method compares two strings, and returns true if the strings are equal, and false if not. Tip: Use the compareTo() method to compare two strings lexicographically.


1 Answers

Doesn't eliminate the extra underlying comparisons, but for the sexiness factor, you could use something like this:

(strA ?? "") == (strB ?? "") 

or the slightly less sexy, but preferable form:

(strA ?? string.Empty) == (strB ?? string.Empty) 
like image 136
iammichael Avatar answered Sep 22 '22 17:09

iammichael