Explain boxing and unboxing with examples in C# languages.
Explain boxing and unboxing with examples.
211
10-Jun-2025
ICSM Computer
12-Jun-2025What is Boxing and Unboxing in C#?
Definitions
Why Does It Happen?
C# treats value types and reference types differently:
object, it must be boxed (copied to the heap).Example: Boxing
What happens:
numberis a value type.object obj, it's boxed.number.Example: Unboxing
InvalidCastException.Example with Error:
Even though both
intanddoubleare value types, the boxedintcannot be unboxed to adouble.Performance Impact
Example with Collection
Before generics:
With generics (avoids boxing):
Summary