There are cases when an instance of a value type needs to be treated as an instance of a reference type. For situations like this, a value type instance can be converted into a reference type instance through a process called boxing. When a value type instance is boxed, storage is allocated on the heap and the instance's value is copied into that space. A reference to this storage is placed on the stack. The boxed value is an object, a reference type that contains the contents of the value type instance.
In Wikipedia there is an example for Java. But in C#, what are some cases where one would have to box a value type? Or would a better/similar question be, why would one want to store a value type on the heap (boxed) rather than on the stack?
I think a good example of boxing in c# occurs in the non-generic collections like ArrayList.
I would recommend you 2 nice articles of Eric Lippert
http://blogs.msdn.com/ericlippert/archive/2009/04/27/the-stack-is-an-implementation-detail.aspx
http://blogs.msdn.com/ericlippert/archive/2009/05/04/the-stack-is-an-implementation-detail-part-two.aspx
Here is the quote that I would 100% agree with
In 99% applications developers should not care about why Value types are in stack and not in the heap and what performance gain could we have here. Juts have in mind very simple rules:
Any rules allows exclusions in special cases, but do not try to over-optimize.
p.s. I met some ASP.NET developers with 2-3 years experience who doesn't know the difference between stack and heap. :-( I would not hire such a person if I'm an interviewer, but not because boxing/unboxing could be a bottleneck in any of ASP.NET sites I've ever seen.
There is almost never a good reason to deliberately box a value type. Almost always, the reason to box a value type is to store it in some collection that is not type aware. The old ArrayList, for example, is a collection of objects, which are reference types. The only way to collect, say, integers, is to box them as objects and pass them to ArrayList.
Nowadays, we have generic collections, so this is less of an issue.
Below is some examples of boxing/unboxing
One example would when a method takes an object parameter and a value type must be passed in.
One of the situations when this happens is for example if you have method that expect parameter of type object and you are passing in one of the primitive types, int for example. Or if you define parameter as 'ref' of type int.