short res = shortA + shortB result in compiler error. Why?

N

nyhetsgrupper

The following code result in the following compilation error: Error 1
Cannot implicitly convert type 'int' to 'short'. An explicit conversion
exists (are you missing a cast?)

short a = 1;
short b = 2;
short result = a + b;

Can anyone explain why??
 
D

Diogene Laerzio

1 e 2 sono int. Prova con:

short a = (short) 1;
short b = (short) 2;
short result = a + b;


(e-mail address removed) ha scritto:
 
D

Diogene Laerzio

1 e 2 sono interi. Prova con:

short a = (short) 1;
short b = (short) 2;
short result = a + b;

Funziona?

(e-mail address removed) ha scritto:
 
D

Diogene Laerzio

1 e 2 are integers. Try:

short a = (short) 1;
short b = (short) 2;
short result = a + b;


OK?



(e-mail address removed) ha scritto:
 
B

Bobbo

Diogene said:
1 e 2 are integers. Try:

short a = (short) 1;
short b = (short) 2;
short result = a + b;

That doesn't work in my version (2005) because it's the result of the
addition that is an int, not the internal value of a and b.
 
J

Jon Skeet [C# MVP]

Diogene said:
1 e 2 are integers. Try:

short a = (short) 1;
short b = (short) 2;
short result = a + b;

The first two lines were fine before - the compile can tell they're
numeric literals.

The issue is that there's no short operator+ (short, short) - only int
operator+ (int, int).

Basically, the OP needs to cast the result:

short a = 1;
short b = 2;
short result = (short) (a+b);

Jon
 
D

Diogene Laerzio

I was searching a way to overload the plus operator but I couldn't find
it. Is it possible to define a:

"short operator+ (short, short)" ?

or to redefine:

"int operator+ (int, int)" ?

Jon Skeet [C# MVP] ha scritto:
 
G

Guest

The plus operator implicitly up casts the shorts to ints and generates an int
result which can't be implicitly down cast back o a short. So you need to
explicitly cast the sum (short)(a+b). This is like telling the compiler "I
know what I'm doing and it is OK, trust me.".
 
J

Jon Skeet [C# MVP]

Diogene Laerzio said:
I was searching a way to overload the plus operator but I couldn't find
it. Is it possible to define a:

"short operator+ (short, short)" ?

or to redefine:

"int operator+ (int, int)" ?

No. You could write your own utility method:

public static short Add (short x, short y)
{
return (short) (x+y);
}

but I think it would be more effort than just including the casts, to
be honest.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

short can't arithmetic with constant? 4
explicit operator cast --> Specified cast is not valid 1
Casting error - why? 4
C# Byte/Short Mathematics 8
Round 3
using nullable types 1
nullable types 1
using UInt16 2

Top