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

Advanced
-Collapse +Expand C# To/From
To/FromCODEGuides
-Collapse +Expand C# Study Test
PRESTWOODCERTIFIED
-Collapse +Expand C# Store
PRESTWOODSTORE

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

KB101285

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


Comments

0 Comments.
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
8717
Since 7/10/2008
Sales Website: www.prestwood.com Or visit our legacy sales site: 
legacy.prestwood.com


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