Tue 28 Feb 2006
How do you add ToString to a method in VB.NET? Why would you want to?
I was looking through my web stats this morning, a very instructive thing to do. One of the stats I look at is the phrases that people enter into search engines such as Google or Yahoo that bring them to my site. Often these are not what you would expect.
I noticed that someone had entered the phrase adding ToString to a method in VB.NET. They would have found nothing here to help them. This may be a case of closing the door after the horse has bolted, but nevertheless I am going to rectify that situation now.
Everything, and I mean everything, with maybe a few minor exceptions, in .NET is an object. Even fundamental data types such as integer, double, single, long, byte, char, boolean – these are objects. So, of course, is the datatype string, although you can argue how fundamental it is. It sometimes behaves like a normal datatype and sometimes it doesn’t, but that is a story for another time.
Every object in .NET is inherited, ultimately, from the type Object. If you look in the Object Browser from within the Visual Studio .NET IDE you will see all the objects listed in a tree view, and at the base of each object is the Object. It is defined in the System namespace and is described as This is the ultimate base class of all classes in the .NET Framework; it is the root of the type hierarchy.
So, how do you use it? ToString is a function with a return type of string. Because it is in the base class it is also in any inherited class. And within the System.Object class it is defined as overrideable. Within a class in VB.NET you would add it to your class like this:
Public Overrides Function ToString() As String
Return mString
End Function
where mString is whatever you would like the object to display when you call the ToString fuction. It may be a field in the class, or another function.
What good is it? One of the main uses is for displaying objects in list boxes and combo boxes. If you add an object to listbox it is the value returned by the ToString function which is displayed.
The important thing to remember about ToString is that even though it appears to work a bit like a ctype operator, or my be confused with a property, it is a function. And it should also be declared as Public because the class containing it may well be in a different assembly.
I find that it is one of those functions that you expect to be there. After a while you tend to add it to almost all your classes as a matter of course.