Can't implicitly convert type 'int' to 'short'?

I have 3 variables declared as type Int16, but this code refuses 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 for the part where I _used = _cap - _avail; throws this error, Error

1 It is not possible to implicitly convert the type 'int' to 'short'. Explicit conversion exists (are you skipping listing?)

+4
source share
1 answer

Yes, this is because there is no subtraction operator for short ( Int16 ). Therefore, when you write:

 _cap - _avail 

which is effective:

 (int) _cap - (int) _avail 

... with the result int .

You can, of course, simply indicate the result:

 _used = (short) (_cap - _avail); 
+6
source

Source: https://habr.com/ru/post/1447606/


All Articles