Your full service technology partner! 
-Collapse +Expand
Search C# Group:

-Collapse +Expand C# To/From
-Collapse +Expand C# Study Test
-Collapse +Expand C# Store

Prestwood eMagazine

December Edition
Subscribe now! It's Free!
Enter your email:

   ► KBProgrammingC#Language Basics   Print This     
  From the June 2015 Issue of Prestwood eMag
C# Language Basics:
Boxing and Unboxing
Posted 13 years ago on 7/10/2008 and updated 1/28/2009
Take Away:

Boxing is the conversion of a value type to the object type (or to any interface type that is implemented by the value type). Unboxing is the conversion from an object type to a value type (or from an interface type to any value type that is implemented by the value type).

 Tags: boxing , unboxing


Boxing is useful because it allows value types to be treated and used as objects. Unboxing allows the conversion back to the value type.

To box a value type, simply assign the value type variable into an object variable:

int a = 25;
object b = a;

It is possible to explicitly declare the boxing with an (object) typecast, but it unnecessary and never required.

Unboxing requires an explicit typecast:

int a = 25;
object b = a;
int c = (int)b;

Unboxing must check if the object is a boxed value of the value type, if it is not it will throw an InvalidCastException


Share a thought or comment...
Write a Comment...
Sign in...

If you are a member, Sign In. Or, you can Create a Free account now.

Anonymous Post (text-only, no HTML):

Enter your name and security key.

Your Name:
Security key = P147A1
Enter key:
KB Post Contributed By Stephen Berry:
Visit Profile

 KB Article #101285 Counter
Since 7/10/2008
Sales Website: Or visit our legacy sales site:

©1995-2021 Prestwood IT Solutions.   [Security & Privacy]