user1216456
user1216456

Reputation:

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

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);
     }

Upvotes: 4

Views: 1190

Answers (3)

user2117229
user2117229

Reputation: 135

If your still wondering about the ternary option.

 value1_check= this.value1!=null? this.value1.Equals(c.value1):(c.value1!=null?c.value.Equals(this.value):value1_check=true);

Upvotes: 0

Jamiec
Jamiec

Reputation: 136104

Actually, you might want the ?? Operator.

var lhs= this.value1 ?? c.value1 ?? null;
var rhs = c.value1 ?? this.value1 ?? null;
var value1Check = lhs == rhs

Should do the same thing as yours, but almost 100% less readable!

Upvotes: 4

SLaks
SLaks

Reputation: 887385

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

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

Upvotes: 8

Related Questions