When to use .Equals and == (or = in VB) operator.

There is a significant difference in how .Equals method and == operator methods performs. The difference is subject to what type of object it is, whether is a value type or a reference type. With an exception to String which is a reference type which overloads the == operator.

The .Equals method is a virtual method and it is implemented in the Object class. This function can be overridden by any class and where as == is an operator which can be overloaded by any class (Operator overloading). For the valuetypes the default implementation of System.Object methods including .Equals is overridden in System.Valuetype class (MSDN). And for value types “If none of the fields of the current instance and obj(parameter passed to the function) are reference types, the Equals method performs a byte-by-byte comparison of the two objects in memory. Otherwise, it uses reflection to compare the corresponding fields of obj and this instance.” (MSDN). This is a significantly slower especially when reflection is employed to find the equality.

Having said that some of the valuetypes does have .Equals methods which takes in the object to compare which is of the same type of the instance. For reference types .Equals checks content equality and where as == operator looks for referential equality(Is operator in VB.NET).

The overloaded operator == is a more readable way to check the equality especially for value types and for strings which overloads == operator. Hence my suggestion is for value types and for strings always use the operators and when you have to do content equality for reference types use the .Equals() method.

Leave a comment

Create a free website or blog at WordPress.com.

Up ↑