Jon Flanders' Blog

Value types and ToString()

Monday, March 01, 2004 3:54:29 PM (GMT Standard Time, UTC+00:00)

Stan (who always has great posts even if you aren't into MC++ ) has some posts about changes to MC++ in Whidbey relating to boxing.

For the most part boxing and unboxing aren't a big concern, and as he rightly points out, it is mostly hidden from us C#/VB.NET developers.  One thing I try to point out when I am teaching, mostly by the way I write code is that whenever I have a value type (even things like an int), and I need to convert it to a string, I always explicitly call ToString().  I've had more than one student ask me why I do that, because the compiler will certainly sometimes make that call for me if a value type has to be converted to a string and I forget, most often in calls to Console.WriteLine.

So this:

Console.WriteLine(v);

essentially turns into this:

Console.WriteLine(v.ToString());

But one important difference is that when I don't *explicitly* call v.ToString(), the compiler has to box the value type (essentially meaning a second copy of the value type is made on the managed heap).  When I do explicitly call ToString(), *if* the value type has overriden ToString() (which most value types do) I avoid the box instruction (and the copy).  With statement completion in  VS.NET doing this on a regular basis is as easy as typing v.To and then hitting CTRL-SpaceBar to cause VS.NET to fill in the rest of the call.

For those of you writing in VB.NET, remember to go to Tools-Options-Text Editor-Basic and unclick "Hide advanced members" , regardless of what the VB.NET team seems to think, I find it insulting and a continuation of the negative stereotyping of VB.NET developers to not allow them to see ToString on the statement completion list ;-)

VS.NET | .NET   #    Comments [0]   

All comments require the approval of the site owner before being displayed.
Name
E-mail
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):

Live Comment Preview