In C #, what is the best way to compare strings with null and & ldquo; & Rdquo; Return true

advertisements

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


While the other answers are good, I would pull them out into their own method to make it clearer to the reader:

public static bool StatesEqual(string first, string second)
{
  return first ?? "" == second ?? "";
}

This will be beneficial if you compare these states in multiple places, or allow you to handle other odd cases if there are any. (Examples might be to change it to be case insensitive, or if two states are textually different but one is an abbreviation of another, i.e. you want "WI" to be equal to "Wisconsin".