if then else vs the ternary operator ( ? :) in c#

c#

Solution

You can call `Object.Equals()`, which already does all that.

return Equals(this.Value1, c.Value1)
    && Equals(this.Value2, c.Value2);

Problem

`this.value1` and `c.value1` can both be either null or non-null. So a total of 4 combinations to test. `value2` can also be null or non-null. Can the if-then-else's below be replaced by something shorter like use the ternary operator ( if then else using the `? :` operators) - and would that be a bad practice for this specific case because we are testing 4 combinations for `value1` and `value2`? ``` public override bool Equals(object obj) { bool value1_check = false; bool value2_check = false; var c = obj as ObjectType; if (this.value1 != null) value1_check = this.value1.Equals(c.value1); else if ((this.value1 == null) && (c.value1 == null)) value1_check = true; else if ((this.value1 == null) && (c.value1 != null)) value1_check = c.value1.Equals(this.value1); if (this.value2 != null) value2_check = this.value2.Equals(c.value2); else if ((this.value2 == null) && (c.value2 == null)) value2_check = true; else if ((this.value2 == null) && (c.value2 != null)) value2_check = c.value2.Equals(this.value2); return (value1_check && value2_check); } ```

Original source