String comparisons using Object.Equals() and String.Equals()

It is often confusing that how should we compare the strings and why should one be preferred over others. So to clarify this confusion here are few example which would give you a clear idea that what should be preferred over other.
The very basic approach what we follow is use of == equal operator for string comparisons. Here is why you should not use == equal operator going forward.

 

Code using == equal operator

There are possibilities that we might want to do a case insensitive comparison. The traditional way of doing this is

 

Attention : What if str2 is null?

 

Code using Object.Equals()

So to handle such scenario where we are sure that left hand side would never be null that can be handled is follows

 

Attention : What if str1 and str2 both are null?

 

Code using String.Equals()

So to handle such scenario where we are both strings can be null that should be handled as follows

 

So the conclusion is strings should be compared in following ways

1. Comparison when one value is certain

 

2. Comparison when both values are uncertain

 

Usage : StringComparison Enum

StringComparison enums

 

References

  1. MSDN : StringComparison enum

Leave a Reply

Your email address will not be published. Required fields are marked *