Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I unbox a string?

What I understand unboxing is when I take a object and unbox it to valuetype like the MSDN example:

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

So I just was thinking, can a string be unboxed? I think, No it can't because there is no valuetype that can represent a string. Am I right?

like image 925
Simon Edström Avatar asked Mar 23 '12 16:03

Simon Edström


People also ask

What is consequence of boxing and unboxing?

Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the common language runtime (CLR) boxes a value type, it wraps the value inside a System. Object instance and stores it on the managed heap. Unboxing extracts the value type from the object.

What is the difference between unboxing and boxing?

In boxing, the value stored on the stack is copied to the object stored on heap memory, whereas unboxing is the opposite. In Unboxing, the object's value stored on the heap memory is copied to the value type stored on stack.

Why do we need boxing and unboxing?

Boxing and unboxing enables a unified view of the type system wherein a value of any type can ultimately be treated as an object. With Boxing and unboxing one can link between value-types and reference-types by allowing any value of a value-type to be converted to and from type object.

How performance is affected due to boxing and unboxing?

During process of boxing and unboxing, it may be possible that the performance of conversion is being affected due the large number of items stored in a collection. I've done a bit of research over this and here is my conclusion. As a general conclusion, we can say that an object is equivalent to a 'void *' of c++.


1 Answers

You're right. A string can't be unboxed because only value types are subject to boxing and unboxing; a string is a reference type.

like image 71
Ry- Avatar answered Oct 18 '22 21:10

Ry-