In C#, why does `long total = (long)value;` throw InvalidCastException when the `object value` holds a boxed int?
answer
- two casts that look the same
- the box remembers its exact type
- unbox first, then widen
- enums and their underlying type
basics
~20 sCasting object to long is an unboxing conversion, and unboxing succeeds only for the exact value type that was boxed. The box holds an Int32, so the runtime throws InvalidCastException; unbox to int first, then widen: (long)(int)value.
solid answer
~40 sWhen the operand is typed `object`, `(long)value` compiles to an **unboxing** conversion, not the `int`-to-`long` widening the compiler applies to a typed `int`. Unboxing checks the box's run-time type and copies the value out only if it is exactly `long`; a boxed `Int32` fails with `InvalidCastException` ("Unable to cast object of type 'System.Int32' to type 'System.Int64'."), and a null reference with `NullReferenceException`. The repairs: unbox to the exact type and then widen, `(long)(int)value`; call `Convert.ToInt64(value)`, which goes through the boxed value's `IConvertible`; or test with a pattern, `value is int n`. The one relaxation is enums: a boxed enum unboxes to its underlying integral type, and a boxed integer of that type unboxes to the enum.
code
csharp · 24 linesobject value = 42; // a boxed int
try
{
long total = (long)value; // compiles: object -> long is an unboxing conversion
Console.WriteLine(total);
}
catch (InvalidCastException ex)
{
Console.WriteLine(ex.Message);
}
long viaInt = (long)(int)value; // unbox to the exact type, then widen
long viaConvert = Convert.ToInt64(value); // IConvertible on the boxed int
Console.WriteLine($"{viaInt} {viaConvert}");
Console.WriteLine(value is long); // False: is ignores numeric conversions
if (value is int n)
{
Console.WriteLine(n + 1); // 43
}
object day = DayOfWeek.Friday;
Console.WriteLine((int)day); // 5: a boxed enum unboxes to its underlying typego deeper
Recall that a box remembers the exact type it was made from and unboxes only to that type; a boxed int needs (int) before it can be widened to long.
Explain that the static type of the operand picks the conversion: on object, (long) means unbox, not widen. Show the three repairs and why is and as ignore numeric conversions.
Point to where object-typed values enter real code, such as non-generic collections, object-valued dictionaries, scalar results and deserialized bags, and push typed boundaries so the compiler checks the cast.
Weigh tolerant conversion, which accepts several boxed types but hides a producer that changed what it stores, against strict unboxing that fails fast on the first mismatch.
## Two casts that look the same The cast syntax `(long)x` means different conversions depending on the **static type** of `x`, the type the compiler sees: | Static type of `x` | What `(long)x` means | What happens at run time | |---|---|---| | `int` | implicit numeric conversion (widening) | the value is sign-extended to 64 bits; never fails | | `double` | explicit numeric conversion | the fraction is truncated; never throws in an unchecked context | | `object` | **unboxing** conversion | the box's type is checked; fails unless it is a boxed `long` | With `object value = 42;` the compiler cannot know what the box holds, so the only conversion the language offers from `object` to `long` is unboxing. It emits an unbox-to-`long` instruction and leaves the type check to the runtime. The compiler gives no warning, because the cast is legal; whether it succeeds depends on data only the runtime sees. Here the runtime finds an `Int32` in the box and throws: ```plaintext Unable to cast object of type 'System.Int32' to type 'System.Int64'. ``` ## What the unboxing check accepts Unboxing reads the value straight out of the box's memory, so the runtime insists that the box's type matches the target type. In practice on .NET 10: - **Exact type**: a boxed `int` unboxes as `int`; a boxed `long` as `long`. - **Same size is not enough**: a boxed `uint` cast to `int` throws `InvalidCastException`, even though both are 32 bits. - **Enums and their underlying type**: a boxed `DayOfWeek.Friday` unboxes as `int` (giving 5), and a boxed `int` unboxes as `DayOfWeek`. This is the one cross-type case. - **Null**: unboxing a null reference throws `NullReferenceException`, not `InvalidCastException`. - Unboxing to a nullable value type such as `int?` follows its own rules, covered with nullable value types. ## Repairing the cast When the code knows (or must tolerate) what the box holds, pick one of these: 1. **Unbox, then convert**: `(long)(int)value`. The inner cast unboxes to the exact type; the outer one is the ordinary widening. This fails fast if a producer ever stores something other than an `int`. 2. **`Convert.ToInt64(value)`**: works on any boxed type that implements `IConvertible` (all the numeric primitives, `string` with a parseable number, `bool`). It is tolerant by design, which can also hide a producer that changed what it stores. 3. **Pattern matching**: `if (value is int n) { long total = n; }` tests and unboxes in one step, and a switch expression handles several possible types explicitly while still failing loudly on a surprise: ```csharp long total = value switch { int i => i, long l => l, _ => throw new InvalidCastException($"Unexpected {value.GetType()}"), }; ``` Each arm unboxes to the exact type it names, and the implicit `int`-to-`long` widening happens after the unboxing, on a typed value. ## `is` and `as` on boxed values The type-testing operators follow the same rules as unboxing: - `value is int` is `true`; `value is long` is `false`. The `is` operator considers identity, reference, boxing and unboxing conversions, but **not numeric conversions**. - `value as int` does not compile. `as` returns `null` on failure, so its target must accept `null`; the compiler reports `CS0077: The as operator must be used with a reference type or nullable type ('int' is a non-nullable value type)`. - `value as long?` compiles; how nullable value types box and unbox is covered in their own material. ## Where this bites in real code The bug appears wherever a value travels as `object` and comes back out somewhere else: - a non-generic collection such as `ArrayList` or `Hashtable`, read years after it was written; - a property bag typed `Dictionary<string, object>` filled by one module and read by another; - an API that returns a scalar as `object`, where the producer's column or field type is `int` but the consumer assumes `long`; - values deserialized into `object`, whose run-time type depends on the serializer's choices. Each of these compiles cleanly and fails only when the run-time type differs from the cast. The durable fix is to keep the static type at the boundary (a generic collection, a typed property, a typed result), so the compiler checks the conversion instead of the runtime.
- Why does (long)someInt work on an int local but not on an object holding the same int?The static type picks the conversion. On an `int` local the compiler applies the implicit numeric conversion from `int` to `long` and emits a widening. On `object` the language's only conversion to `long` is unboxing, so the compiler emits an unbox to `long` and leaves the check to the runtime, which finds an `Int32` and throws.
- Why is `value as int` a compile error, and what do you write instead?`as` returns `null` when the conversion fails, so its target type must be able to hold `null`. `int` cannot, and the compiler reports CS0077: The as operator must be used with a reference type or nullable type ('int' is a non-nullable value type). Use a type pattern, `if (value is int n)`, which tests and unboxes in one step.
- Does a boxed uint unbox as int, since both are 32 bits wide?No. On .NET 10, casting a boxed `uint` to `int` throws `InvalidCastException`: the check compares types, not sizes. The cross-type case it does allow is an enum and its underlying integral type, so a boxed `DayOfWeek` unboxes as `int` and a boxed `int` unboxes as `DayOfWeek`.
- A cast from object to long widens a boxed int like any int-to-long conversion.
- Unboxing as long is safe because long is wider than int.
- value as int returns 0 when the box holds something else.
- value is long is true for a boxed int because int converts implicitly to long.
- Unboxing a null object reference returns default(int).