views:

91

answers:

2

If i have some code like the following:

short myShortA = 54;
short myShortB = 12;
short myShortC = (short)(myShortA - myShortB);

Both operands are shorts and it's going into a short so why do i have to cast it?

+11  A: 

Because there's no "short - short" operator. Both operands are promoted to int.

From section 7.7.5 of the C# 3 spec:

The predefined subtraction operators are listed below. The operators all subtract y from x.

  • Integer subtraction:

    int operator –(int x, int y);
    uint operator –(uint x, uint y);
    long operator –(long x, long y); 
    ulong operator –(ulong x, ulong y);
    

    In a checked context, if the difference is outside the range of the result type, a System.OverflowException is thrown.

(And then there's floating point subtraction.)

Jon Skeet
If only they allowed extension operators... ;)
RCIX
Eric Lippert commented on this (in regards to Enums): http://blogs.msdn.com/ericlippert/archive/2005/10/19/fyi-c-2-0-has-a-breaking-change-in-enum-subtraction.aspx
jasonh
I've often wished this in a few languages... but then I remember how many people would abuse the heck out of it.
Matthew Scharley
It's one of those "With great power comes great responsibility" things right up there with monkeypatching and metaprogramming. Highly powerful in the right hands, but can be misused in so many ways.
RCIX
+1  A: 

To make things a little bit easier, you could simply write an extension method like this:

public static class NumericExtensions
{
    public static short Subtract(this short target, short value)
    {
        return (short)(target - value);
    }
}

Others have answered your question... :)

TigerShark