Box object type with variable of reference type

Boxing is when a value type is assigned to an object type. Same thing when a reference type is assigned to an object?

When a type (which is not an object) is assigned, what happens? Is it boxing too?

int num=5; object obj = num; //boxing ////////////////////// MyClass my = new MyClass(); object obj = my; //what is name this convert (whethere is boxing?) 
+4
source share
4 answers

I suppose you mean something like

 string s = "hello"; object x = s; // no boxing, just implict conversion to base-type. 

This works because System.String , like all other classes, comes from System.Object :

 public sealed class String : Object { ... } 
+7
source

Boxing is when a value type is assigned to an object type.

To close. A β€œbox” occurs when a value of a value type is converted to a reference type.

Is the value of the reference type assigned to the type variable of the object?

Not. Boxing occurs when a value of a value type is converted to a reference type. Converting a value of a reference type to an object is not a conversion to boxing, it is a reference conversion.

When a reference type value (which is not an object) is assigned to an object type variable, what happens?

The value of the reference type is a reference. When a link is assigned to a variable of an type object, a copy of the link is made in the storage location associated with the variable.

Is it boxing too?

Not. Boxing occurs when a value of a value type is converted to a reference type. Converting a value of a reference type to an object is not a conversion to boxing, it is a reference conversion.

+16
source

Boxing creates a reference to an object on the stack that references a value of type say, for example. int, on the heap. But when a reference type (a witch is not an object) is assigned to an object, it does not box.

+2
source

Eric's answer is in accordance with the ECMA-335 CLI (Common Language Infrastructure) standard, section I (architecture), chapter 5 (terms and definitions), which defines the box as: "Converting a value having a value type to a newly allocated instance of the System reference type. Object. " and unpacking as: "Converting a value of type System.Object, whose run-time type is the value type, for an instance of the value type."

The CIL (Common Intermediate Language) instructions for boxing and unpacking behave this way, and this also means what is usually meant when talking about boxing / unpacking in the context of C # or VB.NET.

However, the terms β€œboxing” and β€œunpacking” are sometimes used in a broader / pragmatic sense. For example, the F # field and unbox statements can convert value types and link types to and from System.Object and from System.Object:

 > let o = box "Hello World";; val o : obj = "Hello World" > let s:string = unbox o;; val s : string = "Hello World" 
+1
source

Source: https://habr.com/ru/post/1394139/


All Articles