Tech Embassy

Tuesday, October 24, 2006

Data Types: Checking for Equality

There are three ways to check for equality
1 - the == operator
2 - the Static Equals method
3 - the instance Equals method

When you use any of the above methods for any reference type, by default it does a reference equality check, which means it check if the two objects are the same one (point to the same instance)
If you want to change this behavior, you have to write your own implementation for those methods in your code.
An example of this, is the System.String class, which overrides all the above methods to check for value equality.


For the value type, the story is different
When you define a value type (struct in c#, structure in VB), then by default this value type will do value checking.
The CLR actually uses reflection, to check the members of the value type, and do equality check for each one.
So if your customized value type contains only primitive values (int, double, string,..) then you don't have to override the above methods
But you might need to override them if you are concern about the performance
Reflection is slow, and overriding them will call your decleared method and avoid using the reflection.
Or you want to override them if your value type contains non-premitive data types, or you want to do customized equality check

for all reference type, you have to override this equality check otherwise it does a reference equality check.

what is the difference between all of those methods?

The static equals is going to call the instance equals, but first it check if the values are null
Static Equals is better to use for the following reason

If you use instance equals and one of the object was null, then null reference exception will be generated, where is static equals will handle this and return false.
We know that Exceptions are expensive, so avoiding them is better.

But otherwise the Static equals will end up calling the instance equals.

the == operator is different.
it is checking for reference equality, so if you override the Equals method, then you better override this operator as well, or use Equals all the way

0 Comments:

Post a Comment

<< Home