What is boxing and unboxing?
Experience Level: Junior
Tags: .NET C# Performance
- Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap.
- Unboxing extracts the value type from the object.
- Boxing is implicit
- Unboxing is explicit.
In relation to simple assignments, boxing and unboxing are computationally expensive processes.
- When a value type is boxed, a new object must be allocated and constructed.
- To a lesser degree, the cast required for unboxing is also expensive computationally.
Follow up questions
- How does boxing and unboxing impact performance?
- How to avoid the performance hit of boxing/unboxing?
- What is the difference between stack and heap?
Related C# job interview questions
.NET C# Code challenge Senior
.NET C# Entity Framework LINQ Performance Senior
.NET C# Performance Mid-level
Could you explain what the following LINQ methods OrderBy, Where and Single do and what will be the output of the code?.NET C# LINQ Junior
Could you explain on the following example what a deferred execution is and what materialization is? What will the output be?.NET C# LINQ Performance Mid-level