Logo 
Search:

C# FAQ

Submit Interview FAQ
Home » Interview FAQ » C#RSS Feeds

so an int is a value type, and a class is a reference type. How can int be derived from object?

  Shared By: Emily Brown    Date: Dec 10    Category: C#    Views: 642

Answer:

It isn't, really. When an int is being used as an int, it is a value. However, when it is being used as an object, it is a reference to an integer value (on the managed heap). In other words, when you treat an int as an object, the runtime automatically converts the int value to an object reference. This process is called boxing. The conversion involves copying the int to the heap, and creating an object instance which refers to it. Unboxing is the reverse process - the object is converted back to a value.

int x = 3; // new int value 3 on the stack
object objx = x; // new int on heap, set to value 3 - still have x=3 on stack
int y = (int)objx; // new value 3 on stack, still got x=3 on stack and objx=3 on heap

Share: 
 



Your Comment
  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].


Tagged: