Jan Zahradník
Jan Zahradník

Reputation: 2497

Why does the return type change depending on if I use a ternary operator or not?

I have two IMHO identical piece of code (even Rider suggest me to shorten the 2nd with the 1st option), but giving different results (.NET 8)

public static object Foo1()
{
    int valTrue = 5;
    decimal valFalse = 10m;
    return true ? valTrue : valFalse;
}

public static object Foo2()
{
    int valTrue = 5;
    decimal valFalse = 10m;
    
    if (true)
        return valTrue; 
    else
        return valFalse;
}

If I run them like this:

Console.WriteLine(Foo1().GetType().Name);
Console.WriteLine(Foo2().GetType().Name);

The output of Foo1, which uses the ternary operator, returns Decimal, while the output of Foo2, which uses an if statement, returns Int32. Why is that?

Upvotes: 2

Views: 107

Answers (1)

Joel Coehoorn
Joel Coehoorn

Reputation: 415820

For the first option, if the types of the two results of the ternary expression don't match exactly, there must be an implicit conversion from one to the other, and first the eligible option is selected.

For an int -> decimal conversion, this is a widening conversion (no information is lost because a decimal can express every possible int value), and so an implicit conversion is provided. But the decimal -> int conversion is narrowing (some information is lost, and there's even the potential for an overflow), so an explicit conversion must be used. Therefore the result of the ternary expression is typed as a decimal, regardless of what was true/false for the conditional expression.

For the second option, we have multiple separate expressions, so the compiler is free to use a distinct type for the separate lines.

Both cases feature the return keyword, where the ultimate result is determined by the type used with the method declaration... but again, in the event of a narrowing conversion an explicit cast should be used.

Upvotes: 6

Related Questions