Register to Better Coder! It's free.
Enjoy the premium features and succeed at every job interview.
What is boxing and unboxing?
Experience Level: Junior
- 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
Could you describe what generic type inference is and what will be the output of this program?.NETC#Code challenge Senior
What is the difference between IEnumerable and IQueryable?.NETC#Entity FrameworkLINQPerformance Senior
Do you use generics? What are they good for? And what are constraints and why to use them?.NETC#Performance Medior
Could you explain what the following LINQ methods OrderBy, Where and Single do and what will be the output of the code?.NETC#LINQ Junior
Could you explain on the following example what a deferred execution is and what materialization is? What will the output be?.NETC#LINQPerformance Medior