[Boxing and Casting in C#]

What is the difference between them?

Page 1 of 1

2 Replies - 6925 Views - Last Post: 26 November 2007 - 02:22 PM Rate Topic: -----

#1 Zammy  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 48
  • Joined: 21-October 06

[Boxing and Casting in C#]

Posted 26 November 2007 - 01:34 PM

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.
Is This A Good Question/Topic? 0
  • +

Replies To: [Boxing and Casting in C#]

#2 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4332
  • View blog
  • Posts: 12,127
  • Joined: 18-April 07

Re: [Boxing and Casting in C#]

Posted 26 November 2007 - 01:58 PM

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...

// 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. :)
Was This Post Helpful? 0
  • +
  • -

#3 Zammy  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 48
  • Joined: 21-October 06

Re: [Boxing and Casting in C#]

Posted 26 November 2007 - 02:22 PM

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/
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1