Consider this static test class:
public static class Test { public static ushort sum(ushort value1, ushort value2) { return value1 + value2 } }
This leads to the following compilation error: value1 + value2underlined in red:
value1 + value2
It is not possible to implicitly convert the type 'int' to 'ushort'. Does explicit conversion exist (do you miss the role)?
Why?
Like C and C ++ before it, integers expand implicitly when used with many operators. In this case, the result of adding two values ushortis equal int.
ushort
int
Update:
: http://msdn.microsoft.com/en-us/library/aa691330(v=VS.71).aspx
, C/++, int ( , int, short 32- ). #.
short
/ . .
, int.
ushort z = x + y; // Error: conversion from int to ushort
, cast:
ushort z = (ushort)(x + y); // OK: explicit conversion
# int, uint, long ulong, ushort int, int, ushort.
uint
long
ulong
# 4.0, 7.8.4 , , :
int operator +(int x, int y); uint operator +(uint x, uint y); long operator +(long x, long y); ulong operator +(ulong x, ulong y);
:
.
This is because adding or subtracting abbreviations does not necessarily result in a reduction. For example, the result may be <0, which is not a shorthand. Therefore, you need to give the compiler a hint so as not to complain about the type. I believe this should work: return (ushort) (value1 + value2);