
How Do You Overload == Operator in C# (C Sharp) ?C# supports
operator overloading for a particular set of operators. One among them
is the comparison operator ==. This operator is used for performing
equality function and it is also termed as referential equality. Here is an
example of == operator: Output of
this code will be: obj1 and
obj3 are referentially equal In this example,
members of obj1, obj2 and obj3 have the same value. But only obj1 and
obj3 are referentially equal. This is because obj1 and obj2 are two different
instances of sampleClass created using new operator. The object obj3 is
not newly created using new operator. It is referencing to the same object
obj1 using the statement obj3 = obj1. Hence they are referentially equal. C# gives
you an option to overload this == operator. By overloading you can change
its meaning. But you have a restriction, if you overload the comparison
operator == then you should overload the comparison operator != and vice
versa. To understand how to overload == operator; consider the scenario
given below along with its code sample. As already
discussed, == operator checks for reference equality. When two objects
are referentially equal then it is obvious that they share the same value.
But when two objects share the same value, it is not necessary that they
are referentially equal. Now you are
going to overload this operator to return true if the values of two objects
of the same class are equal. Overloaded == operator is not going to check
if objects hold the same references. This overloading is demonstrated
in the code sample below: class sampleClass
{ Output of
this code will be: obj1 and
obj2 are referentially equal You might
be surprised with the output of this example when compared to the earlier
example. In this example obj1 and obj2 are two different objects of sampleClass
created using new operator. Members of both these objects share the same
value. In normal
scenario, obj1 == obj2 will surely fail. But in this example, you have
overloaded ==operator to check for value of the members instead of the
object references. Hence obj1==obj2 returns true. Similarly obj2 == obj3
will return true. obj1 is reference to the object obj3. Hence they always
share the same value as that of obj3 and hence they also return true. Note that
in the above example, you have also overloaded != operator since comparison
operators should be overloaded in pairs. In addition, you have overridden
the Equals method and GetHashCode method.
_______________________________________________________________________
FREE
Subscription
Subscribe
to our mailing list and receive new articles Note
: We never rent, trade, or sell my email lists to Visit
.NET Programming Tutorial Homepage ______________________________________________________ |