C # Ternary operator evaluating when it shouldn't

This piece of code caught me today:

clientFile.ReviewMonth == null ? null : MonthNames.AllValues[clientFile.ReviewMonth.Value]

clientFile.Review month is a byte? and its value in the failed case is null. The expected result type is a string.

The exception is this code.

    public static implicit operator string(LookupCode<T> code)
    {
        if (code != null) return code.Description;

        throw new InvalidOperationException();
    }

The right side of the score is evaluated and then implicitly converted to a string.

But my question is, why is the right side evaluated at all, when it is clear that only the left side needs to be evaluated? (The documentation states that "only one of the two expressions is evaluated.")

The solution, by the way, is to pass the null value to the string - this works, but Resharper tells me that the listing is redundant (and I agree)

: " "? , - .

+4
2

, . , null LookupCode<T> (- , ), ; .

void Main()
{
  byte? reviewMonth = null;

  string result = reviewMonth == null 
                  ? null // Exception here, though it not easy to tell
                  : new LookupCode<object> { Description = "Hi!" };

  result.Dump();
}

class LookupCode<T>
{
  public string Description { get; set; }

  public static implicit operator string(LookupCode<T> code)
  {
      if (code != null) return code.Description;

      throw new InvalidOperationException();
  }
}

, - null ( a default(LookupCode<object>)) string, . .

, , :

string result = reviewMonth == null 
                ? default(LookupCode<object>) 
                : "Does this get evaluated?".Dump();

- , . , , : ; . :

ldnull      
call        LookupCode`1.op_Implicit

:)

: null, default(string). R # - (string)null null , R # .

, # (14.13 - ):

?: .

X Y . ,

  • X Y , .
  • , (§13.1) X Y, Y X, Y .
  • , (§13.1) Y X, X Y, X .
  • , .

LookupCode<T> string, , LookupCode<T> string. , , , LHS :

string result = ... // Fails
var result = ... // Works fine, var is of type LookupCode<object>
+3

, (, , InvalidOperationException - ((Nullable<byte>)(null)).Value)

, , . , :

clientFile.ReviewMonth == null ? null : MonthNames.AllValues[clientFile.ReviewMonth.Value]

(string)(clientFile.ReviewMonth == null ? (Nullable<LookupCode<byte>>)null : (Nullable<LookupCode<byte>>)MonthNames.AllValues[clientFile.ReviewMonth.Value]);

clientFile.ReviewMonth == null ? (string)null : (string)MonthNames.AllValues[clientFile.ReviewMonth.Value]);

resharper .

-2

Source: https://habr.com/ru/post/1660653/


All Articles