Why is my adding 2 short circuits causing a compilation error due to ints?

In my code, I have the following code:

Order = config.DeploymentSteps.Select(x => x.Order).DefaultIfEmpty().Max() + 1; 

This gives me Cannot implicitly convert type 'int' to 'short' error Cannot implicitly convert type 'int' to 'short' . As references, Order and x.Order are both shorts, and Max() correctly returns a short (I checked this). Therefore, I realized that 1 is integer and error. So I changed it to:

 Order = config.DeploymentSteps.Select(x => x.Order).DefaultIfEmpty().Max() + (short)1; 

Now I still get the same compiler. So maybe this is not the right solution, so I tried changing it to

 Order = config.DeploymentSteps.Select(x => x.Order).DefaultIfEmpty().Max() + Convert.ToInt16(1); 

But I still get the same error. Finally, I got it to work, converting the entire expression:

 Order = Convert.ToInt16(config.DeploymentSteps.Select(x => x.Order).DefaultIfEmpty().Max() + 1); 

Why can't I put 1 to a short and add it to another short without dropping it all?

+3
source share
3 answers

This is because short + short = int.

Eric Lippert explains it here .

He says:

Why short or short result in int?

Well, suppose the short plus short was short and looked at what would happen:

short [] prices = {10000, 15000, 11000}; short average = (prices [0] + prices [1] + prices [2]) / 3; And on average, of course, -9845, if this calculation is performed in shorts. The sum is larger than the largest possible shortest, so it wraps up to negative, and then you divide the negative number.

In a world where whole arithmetic wraps around it are much more reasonable to do all the calculations in int, a type that probably has a sufficient range for typical calculations to not overflow.

+5
source

As far as it sounds redundant, could you declare a short variable (or possibly a constant), and initialize it to 1 and use it when assigning the variable Order. Unlike int or long, there is no literal way to specify short.

+1
source

The C # language specification (download link) contains a list of predefined addition operators. For integral types, this is:

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

The reason you have to quit is the lack of a specific operator to add shorts. I know that "because C # is made to work," this is not a very useful answer, but you go. I would just go with:

 Order = (short) config.DeploymentSteps.Select(x => x.Order).DefaultIfEmpty().Max() + 1; 

or

 Order = config.DeploymentSteps.Select(x => x.Order).DefaultIfEmpty().Max(); Order++; 
+1
source

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


All Articles