If then also vs ternary operator (? :) in C #

this.value1and c.value1can be either null or nonempty. Thus, a total of 4 combinations for testing. value2can also be null or nonempty.

Is it possible to replace if-then-else lower with something shorter than using a ternary operator (if you still use operators ? :) - and this will be bad practice for this particular case, because we are testing 4 combinations for value1and 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);
     }
+3
source share
4 answers

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

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

Actually, you may need ? The operator .

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

, , 100% !

+4

if-then-else - , ?

..

a If Condition Then Else Statement , , IF Condition Else If Condition Then Else Statement, .

, , .

if (this.value1 != null)                  
value1_check = this.value1.Equals(c.value1);           
else if ((this.value1 == null) && (c.value1 == null))   // Comment #1            
value1_check = true;           
else if ((this.value1 == null) && (c.value1 != null))   // Comment #2           
value1_check = c.value1.Equals(this.value1);   

# 1 - , this.value1 null, if ? , , c.value1 null

# 2 - ... this.value1 , , . , c.value1 , (* else *) if .

, :

    if (this.value1 != null)                  
    {
        value1_check = this.value1.Equals(c.value1);           
    }
    else if ( c.value1 != null )
    {
        value1_check = c.value1.Equals(this.value1);   
    }
    else // c.value1 is equal to null
    {
        value1_check = true;  
    }

, SLaks - .

0

.

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

All Articles