Confusion Regarding Boxing Value Types

In the following code ...

 int i=5;  
 object o = 5;
 Console.WriteLine(o); //prints 5

I have three questions:

1) What additional / useful functions will be obtained 5that are in the variable o, which do not have 5, represented by the variable i?

2) If some code expects a value type, we can simply pass it int i, but if it expects a reference type, it is probably not interested in 5 placed in the field oanyway. So, when are box conversions explicitly used in code?

3) How did you Console.WriteLine(o)print 5 instead of System.Object?

+3
source share
4 answers

/ 5, o, 5, i, ?

, - , . .NET , object (, ArrayList ). , , .

- , int i, , , , 5 . , ?

. , , . , .

Console.WriteLine(o) 5 System.Object?

ToString - object, , , . int ToString , int.ToString, , object.

object o = 5;
Console.WriteLine(o.GetType());  // outputs System.Int32, not System.Object
+5

/ 5, o, 5, i, ?

, , , , , .

, ?

, int object, ( , ).

Console.WriteLine(o) 5 System.Object?

ToString . , IFormattable , ( int), ToString, . "5".

0

1) . , - , , . , . , . ( , , , 5 , FileStream).

2) , , .

3) WriteLine, , Object.ToString(). , , ToString, (), ( System.Int, int - , System.Object ) , - .

0

: . , :

System.Console.WriteLine("type: {0}", o.GetType());
System.Console.WriteLine("hash code: {0}", o.GetHashCode());

int - , .

XXX: ; . . , , , , object o = 5 NULL ( o = null), - if int i = 5, i .

: , , , . , . , , /.

"5": , , ToString().

0

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


All Articles