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
C#
| 1 2 3 4 |
for(vari=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()!
C#
| 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?
About Joe Zack
Joe is a Software Developer based in Central Florida. If it weren't for ticketing systems he would gladly refactor himself in circles all day long.
These days Joe is excited about JAMstack and Search.
When he is not basking in the glow of a monitor you can find him walking around Cocoa Beach or annoying his wife by playing "music".