Why do we need explicit casting for brevity for an integer literal in a ternary operator?

static void Main()
{
    short x = 3;/* no need explicit casting (short)3 */
    Console.WriteLine(Factorial(x));
}
static short Factorial(short x)
{
    return x == 0 ? 
        (short)1 /* need explicit casting (short)1 */
        :
        (short)(x * Factorial((short)(x - 1)));
}

Why do I need explicit casting shortfor an integer literal in a ternary operator?

+4
source share
4 answers

Other answers have good ideas, but none of them characterizes the actual problem. This is because you discovered a pretty subtle problem! I discovered the same problem in 2006 when I first worked on a conditional statement in the context of getting type inference working in LINQ. My series of articles on this topic can be found here:

http://blogs.msdn.com/b/ericlippert/archive/2006/05/24/type-inference-woes-part-one.aspx

http://blogs.msdn.com/b/ericlippert/archive/2006/05/26/type-inference-woes-part-two.aspx

http://blogs.msdn.com/b/ericlippert/archive/2006/05/30/type-inference-woes-part-three.aspx

http://blogs.msdn.com/b/ericlippert/archive/2006/07/18/type-inference-woes-part-four.aspx

.

+3

(bool) ? (short) : (int) int, (int) short.

, int short, , , , , , , .

+5

int short ( constant , ). Implicit Numeric Conversions Table (C# Reference)

?: Operator (C# Reference)

condition ? first_expression : second_expression;

first_expression second_expression ,

EDIT: hdv . return ( ). :

var i = x == 0 ?
      1 
      :
      (short)(x * Method((short)(x - 1)));

. i int. short, .

+2

?: type, .

int short, .

MSDN: ?: Operator

first_expression second_expression , .

EDIT:

:

1: .

, , , , :

var result = ( x == 0 ) ? 1 : (short)(x * Method((short)(x - 1)));

:

= > 1 int.
= > int (, short int)

, int, , .

?

, short short

+1

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


All Articles