Reputation: 732
I've tried
module Program
{
Main() : void
{ mutable x : byte = 0B;
mutable y : byte = 0B;
x++;
//y = x + 1;
//y = x + 1B;
//def one:byte=1;// x = x + one;
}
}
No matter which one I try, I get the following error message.
Error 1 expected byte, got int in assigned value: System.Int32 is not a subtype of System.Byte [simple require]
Only way I've found that works is
y = ( x + 1 ):>byte
Which is bit of faff, just to add one.
Why is this? and Is there a better (read shorter way)?
Upvotes: 5
Views: 12162
Reputation: 14041
As in C#, the result of the sum of a byte
and a byte
in Nemerle is an int
. However, unlike C#, Nemerle tries to keep the core language as compact as possible, keeping all of the syntax sugar in the standard macro library. In this spirit, the +=
and ++
operators are macros that are translated into regular addition.
To answer your question, (x + 1) :> byte
is the way to do it. It actually is not all bad, because it lets the reader of your code know that you are aware of the danger of overflow and take responsibility for it.
Still, if you feel strongly about it, you can easily write your own +=
and ++
macros to perform the cast. It would only take a few lines of code.
Upvotes: 8
Reputation: 941595
It is because the CLR defines only a limited number of valid operands for the Add IL instruction. Valid are Int32, Int64, Single and Double. Also IntPtr but that tends to be disabled in many languages.
So adding a constant to a byte requires the byte to be converted to an Int32 first. The result of the addition is an Int32. Which doesn't fit back into a byte. Unless you use a bigger hammer. This is otherwise healthy, the odds that you overflow Byte.MaxValue are pretty large.
Note that there are languages that automatically cast, VB.NET is one of them. But it also automatically generates an OverflowException. Clearly not the one you are using, nor C#. This is a perf choice, the overflow test is not that cheap.
Upvotes: 2
Reputation: 244837
Disclaimer: I don't know Nemerle, but I'm assuming it behaves similar to C# in this regard.
There is a better and shorter way: don't use bytes.
Why are you using them in the first place? Most of the time, computations with int
s are faster than using byte
s, because today's computers are optimized for them.
Upvotes: 1
Reputation: 1
This is what the type system does. Additions upgrade values to ints and then performs the operation resulting in a int. Also have thought what should happen if starting value was 255?
Upvotes: 0