Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C#, what is the best way to compare strings with null and "" return true

I have the following code (as i am trying to detect changes to a field)

 if (person.State != source.State)
 {
      //update my data . .
  }

the issue is I am having cases where person.State is NULL and source.State is "" and thus returning true.

If one is null and the other is an empty string, I want to treat them as equal and don't update my data. What is the cleanest way of doing that? Do i need to create my own Comparer object as this seems like a generic problem

like image 800
leora Avatar asked Aug 16 '12 21:08

leora


People also ask

What does |= mean in C?

The bitwise OR assignment operator ( |= ) uses the binary representation of both operands, does a bitwise OR operation on them and assigns the result to the variable.

What is ?: operator in C?

C operators are one of the features in C which has symbols that can be used to perform mathematical, relational, bitwise, conditional, or logical manipulations. The C programming language has a lot of built-in operators to perform various tasks as per the need of the program.

What is %d in C programming?

In C programming language, %d and %i are format specifiers as where %d specifies the type of variable as decimal and %i specifies the type as integer. In usage terms, there is no difference in printf() function output while printing a number using %d or %i but using scanf the difference occurs.


1 Answers

You'd think there would be a StringComparison enum value to handle this with String.Equals... or a CompareOptions enum value to handle it with String.Compare... but there is not.

In any case, I think you should still be using String.Equals as a best practice.

string s1 = null;
string s2 = string.Empty;

bool areEqual = string.Equals(s1 ?? string.Empty, s2 ?? string.Empty);

// areEqual is now true.

And like this you can add case or culture string compare options easily...

bool areEqual = string.Equals(s1 ?? string.Empty, s2 ?? string.Empty, StringComparison.OrdinalIgnoreCase);
like image 114
James Avatar answered Oct 18 '22 13:10

James