Boxing and Unboxing

int x = 8;
// Box
object y = (object)x;
// Unbox
int z = (int)y;

Boxing slows down performance and consumes more memory (more than twice the memory of the original value type).
Boxing can be avoided by using parameterized classes and methods, using generics; in fact this was the motivation for adding generics.

public void BoxedCall(object value)
	 // Perform operation on value
public void NonboxedCall(T value)
 	// Perform operation on value

int x = 7;

Calls to the BoxedCall method will perform a boxing operation on value types, and calls to the NonboxedCAll method will not.
The type parameter for the call to NonboxedCall is inferred based on its usage.
You can specify the type using:


But it is not recommended.

Extracted from: Under the Hood of .NET Memory Management, Chapter 4: Common Memory Problems. ISBN 978-I-906434-75-5

This entry was posted in Generics and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s