When value type is moved to a reference type it’s called as boxing. The vice-versa is termed as unboxing.
Below is sample code of boxing and unboxing where integer data type is converted in to object and then vice versa.
Performance affected due to boxing and unboxing: -
When boxing and unboxing happens the data needs to jump from stack memory to heap and vice-versa which is a bit of memory intensive process. As a good practice avoid boxing and unboxing where ever possible.
Avoiding boxing and unboxing: -
First thing it’s very difficult to avoid boxing and unboxing. For instance most of the time you will moving data from UI objects like text boxes etc to business objects and also vice versa which will demand boxing and unboxing. Below are some key points to remember:-
- First thing is it really necessary to use boxing and unboxing. If it’s unavoidable like moving data from UI text boxes to internal c# data types, then go for it.
- Try to see if you can use generics and avoid it.
Also see the other following .NET interview questions video on boxing and unboxing: -