Q:

What is Boxing and Unboxing in C#?

0

What is Boxing and Unboxing in C#?

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Boxing and unboxing are an important concept in C#. C# Type System contains three data types: Value Types (int, char, etc), Reference Types (object) and Pointer Types. Boxing and Unboxing both are used for type conversions.

Boxing:

The process of converting from a value type to a reference type is called boxing. Boxing is an implicit conversion. Here is an example of boxing in C#.

Consider the following declaration of a value-type variable:

int i= 123;
// Boxing copies the value of i into object o.
Object obj = i;

The result of this statement is creating an object reference o, on the stack, that references a value of the type int, on the heap. This value is a copy of the value-type value assigned to the variable i. The difference between the two variables, i and o, is illustrated in the following image of boxing conversion:

unboxing:

The process of converting from a reference type to a value type is called unboxing. Here is an example of unboxing in C#.

The following statements demonstrate both boxing and unboxing operations:

int i = 123;      // a value type
object o = i;     // boxing
int j = (int)o;   // unboxing

Below image demonstrates the result of the above-mentioned statements:

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# Interview Questions and Answers,You Need To Know

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
What is enum in C#?... >>
<< Distinguish between finally and finalize blocks?...