3

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

B.Balamanigandan
  • 4,713
  • 11
  • 68
  • 130
  • There's no boxing in either case here. Your code doesn't include any value types at all. The statements aren't identical though - one declares a variable of type `List` and the other declares a variable of type `Object`... that affects how you can use the variable later. – Jon Skeet Aug 10 '16 at 06:36
  • `List` is a `class`, not `struct`, so there's no boxing – Dmitry Bychenko Aug 10 '16 at 06:50

3 Answers3

3

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
Zein Makki
  • 29,485
  • 6
  • 52
  • 63
2

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
Community
  • 1
  • 1
Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
1

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

Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112