Welcome to Dream.In.Code
Getting C# Help is Easy!

Join 136,092 C# Programmers for FREE! Get instant access to thousands of C# experts, tutorials, code snippets, and more! There are 1,593 people online right now. Registration is fast and FREE... Join Now!




[Boxing and Casting in C#]

 
Reply to this topicStart new topic

[Boxing and Casting in C#], What is the difference between them?

Zammy
26 Nov, 2007 - 12:34 PM
Post #1

New D.I.C Head
*

Joined: 21 Oct, 2006
Posts: 41


My Contributions
I read a book for C# and .NET development and taught that I understand what is which but I was wrong. Can someone answer with just 2-3 sentence. Thank you.
User is offlineProfile CardPM
+Quote Post

Martyr2
RE: [Boxing And Casting In C#]
26 Nov, 2007 - 12:58 PM
Post #2

Programming Theoretician
Group Icon

Joined: 18 Apr, 2007
Posts: 5,198



Thanked: 213 times
Expert In: C/C++, Java, VB, VB.NET, C#, PHP, Web Development, HTML & CSS, Javascript

My Contributions
Boxing and casting are very similar. When you cast a "value type" item (like an integer, double, or even a structure which lives on what is known as the stack) into an "object type" item (like Object) that lives on the heap, you are boxing. Example...

CODE

// We declare an instance of a car "structure"
MyCar aCar = new Car();

// Take our value aCar and box it up into an "object" called oCar.
// oCar is now an object that lives on the heap. (implicit cast from MyCar to Object type)
Object oCar = new aCar;

// To unbox it, we cast it back to MyCar explicitly
MyCar hisCar = (MyCar)oCar;


So in short, boxing/unboxing is the process of casting from value types to reference types and vice versa. Where would you find most of this done? In something like a for each loop. Where you could box up different data types like integers, doubles, floats into their own Object, store it in an array and the for each could loop through the objects not knowing exactly what they contain. To the loop and array, they are all simply objects.

Hope that helps clear things up. smile.gif


User is offlineProfile CardPM
+Quote Post

Zammy
RE: [Boxing And Casting In C#]
26 Nov, 2007 - 01:22 PM
Post #3

New D.I.C Head
*

Joined: 21 Oct, 2006
Posts: 41


My Contributions
Thank you very much! I was getting confused that is why asked. There are some really wierd unboxing syntax that I have sometimes trouble reading. \o/
User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 12/1/08 08:21PM

Live C# Help!

C# Tutorials

Reference Sheets

C# Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month