boxing and unboxing in int and string

Gaurav Agrawal picture Gaurav Agrawal · Jun 21, 2011 · Viewed 13.7k times · Source

I am little bit confused in boxing and unboxing. According to its definition

Boxing is implicit conversion of ValueTypes to Reference Types (Object).
UnBoxing is explicit conversion of Reference Types (Object) to its equivalent ValueTypes.

the best example for describing this is

int i = 123; object o = i;  // boxing

and

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

But my question is that whether int is value type and string is reference type so

int i = 123; string s = i.ToString();

and

s = "123"; i = (int)s; 

Is this an example of boxing and unboxing or not???

Answer

CodesInChaos picture CodesInChaos · Jun 21, 2011

Calling ToString is not boxing. It creates a new string that just happens to contain the textual representation of your int.

When calling (object)1 this creates a new instance on the heap that contains an int. But it's still an int. (You can verify that with o.GetType())

String can't be converted with a cast to int. So your code will not compile.

If you first cast your string to object your code will compile but fail at runtime, since your object is no boxed int. You can only unbox an value type into the exactly correct type(or the associated nullable).

Two examples:

Broken:

object o=i.ToString();// o is a string
int i2=(int)o;//Exception, since o is no int

Working:

object o=i;// o is a boxed int
int i2=(int)o;//works