Your implementation has a few problems:
if (Prop1 == Prop2) { return true; }
This means that the method will return true if Prop1
equals Prop2
and nothing else is important.
if (Prop2 == Prop1)
This does exactly the same as the one above and, thus, redundant. Checking if Prop1
equals Prop2
is the same as checking if Prop2
equals Prop1
; does that make sense?
The method doesn't return false
, ever! It actually doesn't return in all code paths and, therefore, won't even compile.
When working on any programming problem, you should ask yourself how would you solve it in real life (or if you do it manually).
So, how do you know that three objects are equal (in your mind)? You basically compare two objects together and then compare the third one to either of them. So, in our example, you would think somehow like this:
Does Prop2
equal Prop1
the same? Okay, and does Prop3
also equal Prop1
? If so, then the three are the same.
Now, how do we write this in code? In C#, the logical AND operator is &&
which we use to combine two conditions together. So, we write something like this:
if (Prop1 == Prop2 && Prop2 == Prop3) { /* All three are equal */ }
Or:
if (Prop1 == Prop2 && Prop1 == Prop3) { /* All three are equal */ }
Full example:
public class myObject
{
public decimal Prop1 {get;set;}
public decimal Prop2 {get;set;}
public decimal Prop3 {get;set;}
public bool AreTheyEqual()
{
if (Prop1 == Prop2 && Prop2 == Prop3)
{
return true;
}
else
{
return false;
}
}
}
Test:
public static void Main(string[] args)
{
var obj1 = new myObject();
obj1.Prop1 = 1;
obj1.Prop2 = 1;
obj1.Prop3 = 1;
Console.WriteLine(obj1.AreTheyEqual()); // True;
obj1.Prop3 = 5;
Console.WriteLine(obj1.AreTheyEqual()); // False;
}