B.Balamanigandan
B.Balamanigandan

Reputation: 4875

Boxing and UnBoxing from List to Object in C#

I wish to know my approach is right or wrong ?

Refer the two statements

Case: #1

List<string> person = new List<string>() {
                            "Harry"
                            "Emma"
                            "Watson"
                        }

Case: #2

Object person = new List<string>() {
                            "Harry"
                            "Emma"
                            "Watson"
                        }

Let me know

which statement is boxing and which statement is un-boxing ?

Both statements are equal and identical ???

Upvotes: 3

Views: 2515

Answers (3)

Hamid Pourjam
Hamid Pourjam

Reputation: 20754

None of them. Boxing and unboxing is a mechanism provided to handle value types with unified type system in .NET.

for example:

int i = 4;
object o = i; //boxing, int is boxed in an object
int j = (int)o; //unboxing, an int is unboxed from an object

From MSDN:
enter image description here

Read more about why we need boxing and unboxing.

There is a special case in boxing of nullable types. When a nullable type boxes, it boxes as its value or null. You can not have a nullable value boxed.

int? a = 4;
object o = a; //boxing, o is a boxed int now
Console.WriteLine(o.GetType()); //System.Int32
int? b = null;
o = b; //boxing, o is null
Console.WriteLine(o.GetType()); // NullReferenceException

Upvotes: 2

Suren Srapyan
Suren Srapyan

Reputation: 68655

It is not an boxing or unboxing.

Boxing means that you store the value type into the reference type, and the unboxing is the reverse of boxing.

In your examples both List and Object are reference type.You are only playing with references

int i = 123;
// The following line boxes i.
object o = i;  

o = 123;
i = (int)o;  // unboxing

int -> object boxing

object -> int unboxing

For more see here Boxing and Unboxing

Upvotes: 1

Zein Makki
Zein Makki

Reputation: 30022

There is no boxing because List is a reference type:

Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type

Unboxing extracts the value type from the object. Boxing is implicit; unboxing is explicit. The concept of boxing and unboxing underlies the C# unified view of the type system in which a value of any type can be treated as an object.

Read More : MSDN

This is boxing:

int i = 123;
// The following line boxes i.
object o = i;  

This is unboxing:

o = 123;
i = (int)o;  // unboxing

Upvotes: 3

Related Questions