I get that one instance of a class is not equal to another instance of the same class, even if both instances contain the properties & fields of the instances contain the same values. For example, in the below code, even though both instances of TestClass
have the same value for the TestValue01
and TestValue02
properties, the comparison will equate to false and "Boooo!"
will be printed.
static void Main(string[] args)
{
TestClass testClassInstance01 = new TestClass(1, 1);
TestClass testClassInstance02 = new TestClass(1, 1);
if (testClassInstance01 == testClassInstance02)
{
Console.WriteLine("Woohoo!");
}
else
{
Console.WriteLine("Boooo!");
}
}
class TestClass
{
public int TestValue01 { get; private set; }
public int TestValue02 { get; private set; }
public TestClass(int testValue01, int testValue02)
{
TestValue01 = testValue01;
TestValue02 = testValue02;
}
}
Is it at all possible to force this kind of comparison to equate to true?
The obvious thing to do is to compaire the property values, like below, but I'm curious if this can be avoided.
if (testClassInstance01.TestValue01 == testClassInstance02.TestValue01
&& testClassInstance01.TestValue02 == testClassInstance02.TestValue02)
{
Console.WriteLine("Woohoo!");
}
else
{
Console.WriteLine("Boooo!");
}
EDIT
For completeness, what I was looking for was operator overloading
. Here is the code I require for this example to return true:
class TestClass
{
public int TestValue01 { get; private set; }
public int TestValue02 { get; private set; }
public TestClass(int testValue01, int testValue02)
{
TestValue01 = testValue01;
TestValue02 = testValue02;
}
public static bool operator==(TestClass tc01, TestClass tc02)
{
return tc01.TestValue01 == tc02.TestValue01 && tc01.TestValue02 == tc02.TestValue02;
}
public static bool operator!=(TestClass tc01, TestClass tc02)
{
return tc01.TestValue01 != tc02.TestValue01 || tc01.TestValue02 != tc02.TestValue02;
}
}