Wednesday, June 12, 2013

Boxing and Unboxing in C#


This is one of the most important topics of .net which would not go without being touched in any interview.

Before we actually delve into this topic. We first need to understand the Value and Reference Types.

Value Type: Variables that are value types store data. value types are known as structures. A value type instance, called a value, on the other hand, is allocated inline as a sequence of bytes, the location of which is based on the scope in which it is defined (e.g., on the execution stack if defined as local, on the GC heap if contained within a heap-allocated data structure).
Value types include the following:
·         All numeric data types
·         Boolean, Char, and Date
·         All structures, even if their members are reference types
·         Enumerations, since their underlying type is always SByte, Short, Integer, Long, Byte, UShort, UInteger, or ULong
char x = ‘a’;
X
‘a’

Reference Type: Reference types store references to the actual data. Reference types are also referred to as objects. Reference types are known as classes. An instance of the reference type, called an object, is allocated and managed on the Garbage Collection heap, and all reads, writes, and sharing of it are performed through a reference (i.e., a pointer indirection).
Reference types include the following:
·         String
·         All arrays, even if their elements are value types
  • Class types, such as Form
String a;
a=”Hello”

 







 C# allows us to convert a Value Type to a Reference Type, and back again to Value Types

Boxing: The operation of Converting a Value Type to a Reference Type is called Boxing
Example
int a = 1;
Object o = a; //Boxing

UnBoxing: The operation of Converting a Reference Type to a Value Type is called Unboxing
Example:
int a = 1;
Object o = a; //Boxing
int i = (int)o; //Unboxing


No comments:

Post a Comment