In C#, why does adding two bytes into a byte fail to compile, while assigning an int to a float compiles but may round?
answer
- small integers widen before arithmetic
- narrowing needs a cast
- implicit is not always exact
- float keeps 24 significant bits
basics
~20 sC# adds two bytes as int, and int to byte is an explicit narrowing conversion, so CS0266 demands a cast. int to float is implicit because it never loses magnitude, but a float cannot hold every integer above 16,777,216.
solid answer
~50 sC# has no `+` for `byte`, `sbyte`, `short` or `ushort`: the operands are converted to `int` and the result is `int`. Assigning that to a `byte` is a narrowing conversion, so the compiler reports CS0266 and asks for a cast; `(byte)(a + b)` then keeps the low 8 bits in the default unchecked context (200 + 100 gives 44) or throws `OverflowException` in a checked one. Implicit conversions are the ones C# considers safe for the range, and the docs say plainly that int, uint, long and ulong to `float`, and long and ulong to `double`, can lose **precision** but never an order of magnitude. So `float f = 16_777_217;` compiles and stores 16,777,216 without a warning. Constants are the exception: `byte b = 13;` compiles because the value fits, `byte b = 300;` is CS0031, and `s += 1` on a `short` compiles because compound assignment inserts the cast.
code
csharp · 21 linesbyte low = 200, high = 100;
int total = low + high; // byte + byte is evaluated as int
byte wrapped = (byte)total; // explicit: keeps the low 8 bits
Console.WriteLine($"{total} -> {wrapped}");
int counter = 16_777_217;
float asFloat = counter; // implicit, yet rounds
Console.WriteLine($"{counter} -> {asFloat:F0}");
long ticks = 9_007_199_254_740_993;
double asDouble = ticks; // implicit, yet rounds
Console.WriteLine($"{ticks} -> {asDouble:F0}");
try
{
Console.WriteLine(checked((byte)total));
}
catch (OverflowException)
{
Console.WriteLine("checked cast -> OverflowException");
}go deeper
Recall which direction needs a cast: widening is implicit, narrowing is explicit, and arithmetic on bytes and shorts produces an int.
Explain why int to float is implicit yet lossy, how compound assignment inserts the narrowing cast, and why constants can convert implicitly when they fit.
Spot the silent rounding of large identifiers and counters passed through float or double, and say where a cast truncates versus throws.
Decide which numeric conversions the team's code review flags, such as long identifiers through double or unchecked narrowing casts on external input.
## Implicit and explicit numeric conversions C# defines a conversion between every pair of built-in numeric types, and classifies each one as **implicit** or **explicit**: - An **implicit conversion** happens without any syntax, in an assignment, an argument or an arithmetic expression. The language allows it only where the destination type can hold the whole range of the source type, such as `int` to `long` or any integral type to `double`. - An **explicit conversion** needs a cast expression such as `(byte)total`. It is required where the value might not fit, such as `int` to `byte`, `long` to `int` or `double` to `int`. Without the cast the compiler stops with CS0266: "Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)". The message is a hint, not a recommendation: the cast silences the error, and the developer takes responsibility for what happens to an out-of-range value. ## Why arithmetic on small integers produces int The predefined arithmetic operators exist for `int`, `uint`, `long`, `ulong`, `nint`, `nuint`, the floating-point types and `decimal`, but not for `byte`, `sbyte`, `short` or `ushort`. When a weather station adds two `byte` sensor values, both operands are implicitly converted to `int`, the addition is an `int` addition, and the result is an `int`. That is why each of these fails with CS0266: 1. `byte sum = a + b;` with `byte a, b`. 2. `short t = s + s;` with `short s`. 3. `s = s + 1;`, even though both operands look like shorts. The surprise is that `s += 1;` compiles. For a predefined operator, compound assignment `x op= y` is evaluated as `x = (T)(x op y)` when the result is explicitly convertible back to the type `T` of `x` and `y` is implicitly convertible to `T` (the constant 1 fits a `short`), so the compiler inserts the narrowing cast for you. That cast follows the same overflow rules as a written one. ## Implicit does not mean exact An implicit numeric conversion never loses the **order of magnitude**, but it can lose **precision**. The C# reference lists the cases: `int`, `uint`, `long`, `ulong`, `nint` and `nuint` to `float`, and `long`, `ulong`, `nint` and `nuint` to `double`. A `float` has a 24-bit significand and a `double` a 53-bit one, so large integers are rounded to the nearest representable value: | Source value | Converted implicitly to | Stored value | |---|---|---| | `int` 16,777,217 | `float` | 16,777,216 | | `long` 9,007,199,254,740,993 | `double` | 9,007,199,254,740,992 | | `int` 1,000 | `float` | 1,000 (exact) | No warning appears. A telemetry counter or an identifier that is pushed through a `float` or `double` parameter can silently change, and nothing at compile time or run time reports it. Every other implicit numeric conversion is lossless. There are also **no implicit conversions** between `decimal` and `float` or `double` in either direction: `decimal m = 1.5;` is CS0664 (use an `M` suffix) and `double d = price;` with a `decimal price` is CS0266. ## What an explicit numeric cast does The behaviour of an explicit cast depends on the source type: - **Integral to a smaller integral type**: in the default unchecked context, the extra high-order bits are discarded, so `(byte)300` evaluated from a variable gives 44. In a checked context, an out-of-range value throws `OverflowException`. The overflow-checking context itself is covered in the lesson on numeric precision and overflow. - **`decimal` to an integral type**: the value is rounded toward zero, and an out-of-range result throws `OverflowException`; the .NET 10 SDK throws it even inside `unchecked(...)`. - **`double` or `float` to an integral type**: rounded toward zero; out-of-range behaviour depends on the context and is also part of the numeric precision lesson. ## Constants get special treatment A **constant expression** of type `int` converts implicitly to `sbyte`, `byte`, `short`, `ushort`, `uint`, `ulong`, `nint` or `nuint` when its value fits. So `byte b = 13;` compiles, while `byte b = 300;` is CS0031: "Constant value '300' cannot be converted to a 'byte'". An explicit cast of an out-of-range constant, `(byte)300`, is CS0221 and needs `unchecked(...)` to compile. These checks only apply to constants; a value read from a variable is never range-checked at compile time.
- Why does `byte b = 13;` compile when the literal 13 is an int?A constant expression of type `int` converts implicitly to a smaller integral type when its value fits the destination range. The compiler checks the value itself, so `byte b = 300;` is CS0031. The rule applies only to constants: assigning an `int` variable holding 13 to a `byte` still needs a cast.
- Why does `decimal price = 19.99;` fail to compile, and so does `double d = price;`?C# defines no implicit conversion between `decimal` and `float` or `double` in either direction, because neither range nor precision is a subset of the other. The first line is CS0664, which suggests the `M` suffix (`19.99m`); the second is CS0266 and needs an explicit `(double)price` cast.
- Saying an implicit numeric conversion can never change the value.
- Expecting C# to add two byte values as a byte.
- Believing a cast like (byte)total throws by default when the value is too large.
- Thinking decimal converts implicitly to double because both are fractional.
- Claiming s += 1 and s = s + 1 behave the same for a short.