Explain boxing and unboxing with examples in C# languages.
Explain boxing and unboxing with examples in C# languages.
Student
The Anubhav portal was launched in March 2015 at the behest of the Hon'ble Prime Minister for retiring government officials to leave a record of their experiences while in Govt service .
What 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