Why is C # throwing errors when performing mathematical operations with integer types other than int?

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:

It is not possible to implicitly convert the type 'int' to 'ushort'. Does explicit conversion exist (do you miss the role)?

Why?

+5
source share
4 answers

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.

Update:

: http://msdn.microsoft.com/en-us/library/aa691330(v=VS.71).aspx

, C/++, int ( , int, short 32- ). #.

/ . .

+7

ushort

, int.

ushort z = x + y;   // Error: conversion from int to ushort

, cast:

ushort z = (ushort)(x + y);   // OK: explicit conversion
+5

# int, uint, long ulong, ushort int, int, ushort.

# 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);

:

.

, int.

+2

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);

+1
source

All Articles