P
Peter
The Operator overloading in C# has one limitation which I
have not seen stated explicitly anywhere.
Take the following example
public class A
{
int m_A;
public A(int a)
{
m_A = a;
}
public static bool operator==(A left, A right)
{
return left.m_A == right.m_A;
}
public static bool operator!=(A left, A right)
{
return left.m_A != right.m_A;
}
public static void Main()
{
A a1 = new A(1);
A a2 = new A(1);
System.Console.WriteLine((a1==a2).ToString());
object o1 = a1;
object o2 = a2;
System.Console.WriteLine((o1==o2).ToString());
}
}
I naively expected the output from this to be
true
true
but the actual output is
true
false
Because the operator is statically defined, the version of
== to be called is determined at compile time, hence
object.== is called rather than A.==
So rather than use == you must use the virtual method
Equals if you need to perform equality checks on
polymorphic objects.
This may be obvious to a lot of you folks out there, but it
was not obvious to me until I ran in to trouble with it.
Does anyone have any Idea why it was implemented in this way?
have not seen stated explicitly anywhere.
Take the following example
public class A
{
int m_A;
public A(int a)
{
m_A = a;
}
public static bool operator==(A left, A right)
{
return left.m_A == right.m_A;
}
public static bool operator!=(A left, A right)
{
return left.m_A != right.m_A;
}
public static void Main()
{
A a1 = new A(1);
A a2 = new A(1);
System.Console.WriteLine((a1==a2).ToString());
object o1 = a1;
object o2 = a2;
System.Console.WriteLine((o1==o2).ToString());
}
}
I naively expected the output from this to be
true
true
but the actual output is
true
false
Because the operator is statically defined, the version of
== to be called is determined at compile time, hence
object.== is called rather than A.==
So rather than use == you must use the virtual method
Equals if you need to perform equality checks on
polymorphic objects.
This may be obvious to a lot of you folks out there, but it
was not obvious to me until I ran in to trouble with it.
Does anyone have any Idea why it was implemented in this way?