0 votes
by (2.5k points)
I've heard of the term "boxing" in C# and I don't really understand it.

1 Answer

0 votes
by (2.5k points)

The answer to this really depends on how deep you want to go with it. In short, the most important thing to understand is that there are two types in C#. 

  • Reference types
  • Value types

The former is stored on the heap, and the latter on the stack. (confused yet?)

The term boxing comes when you store a value type on the heap. You generally see it happen with code like so : 

int myValue = 123;
object myValueAsAnObject = (object)myValue;

Notice how I set up an integer, but then I was able to store it as a "object". Doing this would be considered boxing as I took a value type and stored is an object. You might not get such obvious examples out there in the wild but it happens more than you realize. 

The reason that boxing/unboxing is talked about so much is that it's a relatively expensive operation. If you are often converting between value and reference types, there's a cost associated with doing that. So any time you can avoid boxing is considered more "performant" code. 

Welcome to .NET Q&A, where you can ask questions and receive answers from other members of the community.