Unlike Java, C# has a unified type system. Both reference types AND values inherit from system.object which means that you can have a method that takes in both value and reference types by their common parent, System.Object.
This is used to great effect in the String class, where you have methods like CompareTo(Object), String.Concat(Object,Object) and my personal favorite: Format(String, Object[]).
These methods are really convenient, but unfortunately boxing occurs when you pass in value types.
However, we’ve come across a nice trick for skipping those operations.
There will be 99 boxing operations in the following example
1 2 3 4 |
for(var i = 1; i <= 99; i++) { Console.WriteLine("{0} bottles of {1} on the wall", 99, "beer"); } |
However, in researching this post I realized that the ToString() method resides in System.Object. That’s why you can call something like 11.ToString() or affix extension methods to DateTime objects.
ToString() does NOT result in a boxing operation so you can skip the expensive operation by simply calling ToString()!
1 2 3 4 |
// Boxing occurs Console.WriteLine("Take {1} down, pass it around.", 1); // NO BOXING OPERATION! Console.WriteLine("{0} bottles of beer on the wall.", (i--).ToString()); |
Nifty, eh?