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?
short
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
.
(bool) ? (short) : (int) int, (int) short.
(bool) ? (short) : (int)
int
(int)
, int short, , , , , , , .
int short ( constant , ). Implicit Numeric Conversions Table (C# Reference)
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, .
i
?: type, .
?:
type
int short, .
MSDN: ?: Operator
?: 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
Source: https://habr.com/ru/post/1529553/More articles:The difference between Dartium and dart2js when building chrome extensions - dartWhy use trackbacks instead of the HTTP Referer header? - httpThere is no "zip download" button to download a source to .zip on github - githubHow to change a string containing surrogate pairs - stringWork with branch branches - testingPostgres copies data between tables - sqlAn expression tree may not contain an assignment operator? - c #TableHeaderView not responding to touch - iosSass compiler not working in exalted text 3 - sass| not recognized in java string.split () - javaAll Articles