Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# does not let me sum two shorts to a short [duplicate]

I have a code:

static short Sum(short a, short b)
        {
            return a + b;
        }

And it does not compile, saynig cannot convert 'int' to 'short'. I am maybe really tired today but I cannot see the issue!

like image 211
John V Avatar asked Aug 07 '12 20:08

John V


People also ask

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

What do you mean by C?

" " C is a computer programming language. That means that you can use C to create lists of instructions for a computer to follow. C is one of thousands of programming languages currently in use.

What is C language used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...


1 Answers

And it does not compile, saynig cannot convert 'int' to 'short'. I am maybe really tired today but I cannot see the issue!

It's just the way the language is defined. The + operator on integer types is defined for:

static uint op +(uint x, uint y)
static int op +(int x, int y)
static ulong op +(ulong x, ulong y)
static long op +(long x, long y)

Operands are promoted as required.

Now as for the reasons why it's defined that way - I don't know, to be honest. I don't buy the argument of "because it could overflow" - that would suggest that byte + byte should be defined to return short, and that int + int should return long, neither of which is true.

I've heard somewhere that it could be performance related, but I wouldn't like to say for sure. (Perhaps processors typically only provide integer operations on 32 and 64 bit integers?)

Either way, it doesn't really matter why it's the case - it's just the rules of the language.

Note that the compound assignment operators have an implicit conversion back to the relevant type, so you can write:

short x = 10;
short y = 20;
x += y;
like image 121
Jon Skeet Avatar answered Oct 03 '22 14:10

Jon Skeet