First, simply read about boxing and unboxing more thoroughly and think about it.
This should be clear enough:
http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx[
^].
To add to it, I can only respond to your immediate concerns.
First, in all your code samples, conversion to
object
is completely pointless, only the last sample is reasonable. What can I add to your understanding. Even though boxing and unboxing is very important in .NET, immediate using boxing is pretty rare, and using unboxing is even more rare.
Let me explain just
Write
, or, very close in usage
string.Format(string format, params object[] values)
. Look at the last method signature. This is the most universal way to provide passing parameters for formatting of the value of absolutely any type. Let's see how it works. If format string contains only placeholders in "free format" like {0}, {1}, etc., and as each parameter is boxed to
System.Object
, each of the placeholders is substituted with what is returned by
System.Object.ToString
. In other words, the mechanism uses the fact that all objects of all type have
ToString
method. Unboxing is already done in passing of the parameters (due to
assignment compatibility to
System.Object
), and no unboxing is needed. If specific format specifier is used for some of the placeholders (this is called
composite formatting), unboxing is needed for getting type-specific information. For example, if number of significant digits is specified, properties of floating-point arithimetic are used.
—SA