Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
471 views
Welcome To Ask or Share your Answers For Others

1 Answer

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 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...