How to pass x.ToString () to a method that expects an object type, not just x to prevent boxing?

I have a method called OutputToScreen(object o), and it is defined as:

public void OutputToScreen(object o)
{
    Console.WriteLine(o.ToString());
}

In my main calling method, if I do something like:

int x = 42;
OutputToScreen(x); // x will be boxed into an object

But if I do this,

OutputToScreen(x.ToString()); // x is not boxed

I'm still not sure why x does not fit in the box in the second approach, I just saw it on the free video from quickcert. Can anyone give a good explanation?

Here is another comment based question:

If I pass x.ToString (), which looks like:

string temp = x.ToString (); and then going through in temp, boxing still doesn't occur when I insert x into the string type

+5
source share
4 answers

. , , OutputToScreen. , , ToString, .

, . , , . , (1) , ToString, , (2) , ToString . , . ; , , , , , .

, , .

- , .

, , , :

- , x ?

, " ". Int int. , int. . .

, , :

ToString(), , , int , "this" ?

. , # , , . , , , "this" , , , vtable.

int ToString, ToString int int, ToString vtable int, int ToString int. .

, . GetType() . GetType() int, . , GetType(), System.Object . .

, , :

int? x = null;
Console.WriteLine(x.ToString());
Console.WriteLine(x.GetType());

?

Int? ToString, ToString . GetType , x . ; null int? . null.GetType() . , !

:

struct S { /* does not override ToString */ }

S s = new S();
string str = s.ToString();

, , "this".

, . . .

http://blogs.msdn.com/b/ericlippert/archive/2011/03/14/to-box-or-not-to-box-that-is-the-question.aspx

vtable?

vtable - , . . vtable:

#

+13

"", . IL-:

http://weblogs.asp.net/ngur/archive/2003/12/16/43856.aspx

, x.ToString() , .

-, structs (aka types) ToString() . ToString, ToString() .

Int32 :

public override string ToString()
{
   return Number.FormatInt32(this, null, NumberFormatInfo.CurrentInfo);
}

( , ):

int x = 42;
object boxed = x;
OutputToScreen(boxed);

x OutputToScreen. x.ToString() OutputToScreen, (.. ). , (Int32 ) ToString, ToString() . , OutputToScreen .

int x = 42;
string temp = x.ToString();
OutputToScreen(temp);
+6

OutputToScreen, (ToString , , , OutputToScreen). int OutputToScreen, .

+3

System.String, , , .

+2
source

All Articles