How do you override operator == when using interfaces instead of actual types?
Posted
by RickL
on Stack Overflow
See other posts from Stack Overflow
or by RickL
Published on 2010-06-15T11:46:52Z
Indexed on
2010/06/15
11:52 UTC
Read the original article
Hit count: 216
I have some code like this:
How should I implement the operator == so that it will be called when the variables are of interface IMyClass?
public class MyClass : IMyClass
{
public static bool operator ==(MyClass a, MyClass b)
{
if (ReferenceEquals(a, b))
return true;
if ((Object)a == null || (Object)b == null)
return false;
return false;
}
public static bool operator !=(MyClass a, MyClass b)
{
return !(a == b);
}
}
class Program
{
static void Main(string[] args)
{
IMyClass m1 = new MyClass();
IMyClass m2 = new MyClass();
MyClass m3 = new MyClass();
MyClass m4 = new MyClass();
Console.WriteLine(m1 == m2); // does not go into custom == function. why not?
Console.WriteLine(m3 == m4); // DOES go into custom == function
}
}
© Stack Overflow or respective owner