Read the syntax
See how value types become objects and why unboxing requires the correct boxed type.
Reassigning original changes that variable, not the boxed object.
What it is and why to use it
C# can treat an integer or another value type as object. Boxing places a copy of that value in an object representation. Unboxing extracts a value of the boxed type. Understanding the copy and type rules explains both surprising mutations and the overhead avoided by generic collections such as List<int>.
How it works
Assigning a value type to object boxes it implicitly. An explicit cast can unbox a boxed value when its actual type matches. A boxed int cannot be directly unboxed as long, even though an int value can normally convert to long: first unbox int, then convert that value. Reference-type casts do not use these same value-copy rules.
Common mistakes and limitations
Do not assume that changing the original integer updates its earlier boxed copy. Do not use object collections for numeric data when a suitable generic collection is available. Unboxing a mismatched type throws InvalidCastException; unboxing null as a non-nullable value type also fails.
Run the examples locally
These complete Program.cs examples use a .NET 10 console project with the C# language version set to 12.0, nullable checking enabled and implicit usings disabled. They use standard .NET libraries and need no extra NuGet packages. This is the verified environment, not a claim that every API requires .NET 10 or works unchanged in .NET Framework, Unity or other runtimes.
Install a supported .NET 10 SDK, create the console project, replace its project file with the settings below, then replace Program.cs with one complete example at a time. Build and run from the project folder. using directives bring namespaces into scope; top-level statements form the program’s entry point, and any helper types follow those statements. Console.WriteLine writes terminal output. Do not combine examples that declare the same type names.
C# in Codectionary’s Playground is editing-only: it does not compile or execute these programs. Run them with the local .NET SDK to reproduce the expected output. Async examples use controlled in-process operations rather than live network services or timing-sensitive delays.
Create and enter a project
dotnet new console -n CSharpExample --framework net10.0
cd CSharpExampleCSharpExample.csproj settings used for these examples
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>12.0</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
</PropertyGroup>
</Project>Build and run after saving one example in Program.cs
dotnet build
dotnet run --no-buildContinue learning
Change one input and predict the result before running it. Follow the related guides to connect this topic with the surrounding language features.
Syntax
object boxed = 42;
int value = (int)boxed;Examples
Observe that boxing copies a value
Change the original integer after placing its earlier value in an object.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
int original = 7;
object boxed = original;
original = 9;
Console.WriteLine(original);
Console.WriteLine((int)boxed);
- The assignment to object boxes a copy of integer 7.
- Reassigning original changes that variable, not the boxed object.
- The unboxed result remains 7. This copy behaviour differs from two variables referring to the same mutable class instance.
- Expected output: 9 7
- Prefer typed generic collections when their element type is known.
Unbox before a numeric conversion
Handle a wrong direct cast and show the correct two-step conversion.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
object boxed = 7;
try {
long wrong = (long)boxed;
Console.WriteLine(wrong);
} catch (InvalidCastException) {
Console.WriteLine("Box contains Int32, not Int64");
}
long correct = (int)boxed;
Console.WriteLine(correct);
- The runtime box contains an Int32, so a direct Int64 unbox is invalid.
- The specific catch demonstrates the type mismatch without ending the program.
- Casting to int first extracts the correct value; assigning that int to long then performs an ordinary numeric conversion.
- Expected output: Box contains Int32, not Int64 7
- Prefer typed generic collections when their element type is known.
Best practices
- Prefer typed generic collections when their element type is known.
- Check the actual boxed type before extracting an uncertain value.
Runtime & versions
.NET runtime. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
C# language reference