2
I’m creating a simple C# application to calculate some flight information, in which you have a class called Calculator
containing the following methods:
public static float GetDistance(ushort height) {
return height * 3 / 1000;
}
public static uint GetVerticalSpeed(ushort groundSpeed) {
return groundSpeed * 10 / 2;
}
In both methods, I defined the parameters as being of the primitive type ushort
, for they must be equal to or greater than zero, and must have a certain limit, since no aircraft flies above 65536 ft altitude and above 65536 knots speed - which is the maximum value of this primitive type.
The primitive type of return methods is different. In the first method, the return is float
, because I need to get the decimals of the result. Already in the second method, the return is uint
, as the result may be greater than 65535.
The problem is that even having the primitive type of return "compatible" with the maximum result that the method can return, the compiler still generates the following error for the second method:
Cannot implicitly convert type 'int' to 'uint'. An explicit conversion exists (are you missing a cast?)
Also, in the first method, the returned result is always an integer - no floating point - even when it should be a real number.
This leads me to think that the problem of my code is not in the return of methods, but in the line of calculation. I wrote the methods thinking that the calculation would return a value, whose primitive type would correspond to the result. But it seems that’s not what happens.
That said, my question is:
- Arithmetic operations in C# keeps the primitive type of the variable used in the result?
- If yes, how this occurs internally and what I should do to make the result have a primitive type different from the variable?
yes, the compiler does not know how to do this, need for a cast ai in the code to convert to the desired type, in that case
uint
.About your question, the type of variable is immutable if it isint
for example, it will always beint
, and so on. And second question as I mentioned, just make a cast and convert to desired type– Ricardo Pontual
Just to complement, the Typecast explicitly
return (uint)(groundSpeed * 10 / 2);
– Augusto Vasques