RationalDev

more of an aspiration than a claim

Why (string == string) Is A Bad Habit in C# And Other Languages

Whilst (string == string) works as a comparison since strings are immutable in C#, I advise against it for the following reasons:

  • If you move to another language like Java, C++ etc, == comparisons are a bad habit to be in, because there it does matter and makes for much pain.
  • It is easy to type = instead of ==. Whilst visually this is easily to miss, the compiler is infallible and will not be as forgiving as your eye if you make the wrong distinction.
  • It is more explicit to use a method such as .equals, .Compare etc.
  • It is easier to search an explicit string comparison, both visually and with a search tool feature.
  • If your code ever gets converted to another language, this may become an issue. This is more an issue when developing frameworks. Some people will create a StringUtil type class. This can encapsulate your String operations and caters for changing your implementation in one location.