Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot implicitly convert type 'int' to 'short'? [duplicate]

Tags:

c#

.net

I've got 3 variables all declared as type 'Int16', yet this code is refusing to work.

    private Int16 _cap;                 // Seat Capacity
    private Int16 _used;                // Seats Filled
    private Int16 _avail;               // Seats Available

    public Int16 SeatsTotal {
        get {
            return _cap;
        }
        set {
            _cap = value;
            _used = _cap - _avail;
        }
    }

Except the part where I have _used = _cap - _avail; is throwing this error, Error

1 Cannot implicitly convert type 'int' to 'short'. An explicit conversion exists (are you missing a cast?)

like image 736
Mirrana Avatar asked Feb 18 '23 10:02

Mirrana


1 Answers

Yes, that's because there's no subtraction operator for short (Int16). So when you write:

_cap - _avail

that's effectively:

(int) _cap - (int) _avail

... with an int result.

You can, of course, just cast the result:

_used = (short) (_cap - _avail);
like image 142
Jon Skeet Avatar answered Feb 21 '23 18:02

Jon Skeet