다음을 통해 공유


String equality comparison in C#

Options for string equality comparison

Although the subject is pretty trivial, I thought I'd share my two cents on the topic because lately I've seen lots of different implementations, even within a single project. Some of them are:

foo == "bar"  
You can't specify string comparison rules
(in my opinion, this does have the best readability)

foo.Equals("bar")  
If foo is null, throws a NullReferenceException

String.Compare(foo, "bar") == 0 
MSDN doesn't recommend this for checking equality

String.Equals(foo, "bar")  
The most performant way, doesn't throw NullReferenceException and you can also specify comparison rules

 

StringComparison parameter 

There is a recommendation on MSDN to use overloads that explicitly specify the string comparison rules, so you should always call the static method with a StringComparison parameter:

 String.Equals(foo, "bar", StringComparison.OrdinalIgnoreCase)
 

Although string comparison logic rarely has a significant effect on the overall performance, you might consider using OrdinalIgnoreCase for case-insensitive comparison as it is faster than Ordinal (which is the default) and InvariantCultureIgnoreCase.

 

Extension method helper

You could also write an extension method to make your life a bit easier:

 public static bool Eq(this string strA, string strB)
 {
   return String.Equals(strA, strB, StringComparison.OrdinalIgnoreCase);
 }
 

And call the extension method like this:

 if (foo.Eq("bar"))
 {
 ...
 }
 

 

Further reading

Best Practices for Using Strings in the .NET Framework
https://msdn.microsoft.com/en-us/library/dd465121.aspx

Comparing Strings
https://msdn.microsoft.com/en-us/library/fbh501kz.aspx