Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
499 views
in Technique[技术] by (71.8m points)

c# - boxing and unboxing in int and string

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

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

1 Reply

0 votes
by (71.8m points)

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 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...