Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mechanism of Unboxing

When unboxing takes place there is the copy of boxed value into an appropriate variable type but what happens at the memory location of the boxed copy on heap. Is boxed copy remain at that location and cover memory on heap?

like image 303
mdadil2019 Avatar asked May 27 '16 16:05

mdadil2019


People also ask

What is boxing and unboxing explain with example?

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 advantage of boxing and unboxing?

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. The advantage of boxing is that you can pass, say, an integer around as an object. The advantage of unboxing is you get you native integer performance back.

What is unboxing in C sharp?

Unboxing In C# The process of converting a Reference Type variable into a Value Type variable is known as Unboxing. It is an explicit conversion process. Example : int num = 23; // value type is int and assigned value 23 Object Obj = num; // Boxing int i = (int)Obj; // Unboxing.

How can we avoid boxing and unboxing?

How to prevent boxing & unboxing: Use ToString method of numeric data types such as int, double, float etc. Use for loop to enumerate on value type arrays or lists (do not use foreach loop or LINQ queries) Use for loop to enumerate on characters of string (do not use foreach loop or LINQ queries)


1 Answers

Is boxed copy remain at that location and cover memory on heap?

Yes. After all, there could be other references to it:

object o1 = 5;
object o2 = o1;
int x = (int) o1;
x = 10;
Console.WriteLine(o2); // Still 5

Boxed values act like normal objects, in terms of being eligible for garbage collection when there are no more strong references to them.

like image 171
Jon Skeet Avatar answered Oct 17 '22 17:10

Jon Skeet