DevCity.NET - http://devcity.net
Object Oriented Programming Basics - Methods
http://devcity.net/Articles/379/1/article.aspx
Ged Mead

Ged Mead (XTab) is a Microsoft Visual Basic MVP who has been working on computer software and design for more than 25 years. His journey has taken him through many different facets of IT. These include training as a Systems Analyst, working in a mainframe software development environment, creating financial management systems and a short time spent on military laptop systems in the days when it took two strong men to carry a 'mobile' system.

Based in an idyllic lochside location in the West of Scotland, he is currently involved in an ever-widening range of VB.NET, WPF and Silverlight development projects. Now working in a consultancy environment, his passion however still remains helping students and professional developers to take advantage of the ever increasing range of sophisticated tools available to them.

Ged is a regular contributor to forums on vbCity and authors articles for DevCity. He is a moderator on VBCity and the MSDN Tech Forums and spends a lot of time answering technical questions there and in several other VB forum sites. Senior Editor for DevCity.NET, vbCity Developer Community Leader and Admin, and DevCity.NET Newsletter Editor. He has written and continues to tutor a number of free online courses for VB.NET developers.

 
by Ged Mead
Published on 8/11/2009
 

In the previous articles in this series, we covered basic Constructors, Fields and Properties.

In this article, we will look at the ToString method, introduce the concept of Inheritance, use the Object Browser and learn about Overrides and Overridable. 


Introduction

Methods
In the two previous articles we covered the basics of Fields, Properties and Constructors. This article looks at another Class Member - Method.

Of course, you have used methods all the time already in your coding. Subs, Functions, Procedures - you can't get very far without them. Actually, the previous articles covered some methods, because property procedures and constructors are both examples of methods which carry out specialised tasks.

Some people like to think of class members in terms of verbs and nouns - verbs being the "doing" elements and nouns being the "something which exists" elements. Fields and properties in general would be nouns. Constructors and other class methods would be verbs.

The particular method that we are going to look at in this article is the ToString method. Along the way we will take a first look at inheritance and will enlist the help of the Object Browser.

The ToString Method
Just about all .NET Types have a built in ToString method. I'm sure you will have done this or seen it lots of times in the past. Code such as:

This snippet converts an Integer type into its String representation.

In the past, you might not have given much thought to how the ToString method works. And of course you didn't need to. The designer of the Integer Class has devised a ToString method for you to use; you can write client code that takes advantage of that facility and you don't need to know how it works - just as long as it does work!

As the designers of the Person Class though, we should decide what we want to do about offering a useful ToString method for the users of our class.

Person.ToString
You may have noticed that I used the word "useful" in that last sentence. A ToString method does already exist for the Person Class, even though it isn't actually visible in the Class code we have written so far.

When we begin to look at inheritance later, you will discover how that comes about. For the time being though, accept that it does exist but that it won't return a result that is particularly useful unless you do something to improve it.

To see the current situation, try this: Open the Class Basics project and put a Label control on this form. Put the following code in the Form_Load event of Form1 in the project:

Code Copy
        ' Create a new Person Instance
        Dim RealPerson As New Person("Ged", "Mead")
        '  Display using the default ToString method
        Label1.Text = RealPerson.ToString

Here is the result of that code:

   

Chances are this isn't a very useful result in most circumstances. It's accurate enough, but we would usually want a result that displayed some information about one or more properties of the RealPerson instance. You don't get that by default, but as you will see, it's easy to write code that will do just that.

Analyzing Person.ToString
The default version of ToString for the Person class will return (produce) only the name of the Namespace that holds the class and the name of the class itself. The namespace in this case is ClassBasics - which is also the name of the project in Visual Basic unless you change it). The name of the class is, of course, "Person". You can see this in the Solution Explorer screenshot below.

   

 In order to be able to make sense of how that default ToString method works, we are going to take a first peek at the subject of inheritance.

 

Inheritance Basics

Introduction
In its most simple terms, Inheritance in OOP describes the ability of one class to make use of the members of another class. Put another way, if Class B is said to inherit from Class A then Class A (the parent class) hands down its abilities to Class B (a child class).

You may sometimes see this parent/child relationship described as Base class and Derived class or Superclass and Subclass. People often talk about 'subclassing', when they mean they create a new child class, based on a parent. All these terms have the same meaning.

I will describe what inheritance means in more detail in a future article. For now though, just hold on to this general idea that the child inherits the Public members - Methods, Properties, etc - from the parent.

System.Object
When it comes to inheritance in VB.NET, you could think of the System.Object class as being the father of all classes. What I mean by this is that the classes that are built in to the .NET Framework - Integer, DateTime, Size, StreamReader, etc - all inherit directly or indirectly from System.Object.

Classes that you create yourself, like the Person class, will also inherit directly from System.Object. So if System.Object has Public members (and it has) then these should be inherited by your Person Class (and they are).

At this stage we are only interested in one specific Public method - the ToString method. System.Object has a ToString method; therefore your Person class also has a ToString method.

If you use the parent class's ToString method as-is then what you will get is the functionality of the parent's method. That is, in this case, the functionality of System.Object's ToString method. As it happens, the ToString method of System.Object will simply return the name of the class.

So in our earlier example, that is exactly what happened. We used the ToString method to get some information about an instance of our class. As we haven't yet written our own version of ToString for the Person class, VB looked back up the inheritance chain and found the ToString method of the parent class.

As a result, as you saw on the previous page, this is what the ToString method produced:

   

This usually known as the fully qualified name of the class. "Fully Qualified" simple means that all the detail of the name is included - in this case, the namespace name (ClassBasics) and the Class name (Person).

We want to replace the instructions in the ToString method in the parent class with code that is more suitable for the purposes of a Person object. Replacing the instructions in this way is known as Overriding. More on this later.

First though, I want to take a quick tour of the Object Browser.

 

The Object Browser

You can view the parentage of the Person Class in Visual Studio by using the Object Browser. You can bring the Object Browser into view in Visual Studio by selecting View | Object Browser from the menu in the IDE. It is even easier to use the shortcut key - F2.

The Object Browser is the source of a lot of useful information and recent versions are much improved. The layout of the details of the earlier versions could be quite confusing. The left hand side of the initial display will look similar to this in Visual Studio 2008:

   

(If you can't see the Form1 and Person classes in the list in your own copy of the project, you will need to click on the small plus sign at the left hand side of 'ClassBasics'. Once expanded, the plus sign changes to a minus sign, as shown in the screenshot.)

In the screenshot above, the first line is the name of the namespace. Then we have the Form1 class and the Person class as the next two items in that list.

To ensure that what you will see in your project is the same as the screenshots I will be showing you, first click on the small down arrow as shown below:

   


This will reveal list of layout choices. For now, select the 'View Namespaces' and 'Show Public Members' items only, as shown below:

   


If you next click on the word "Person" on the fourth line of the Class listing at the left hand side of the Object Browser (or click the plus sign to the left of it), you will see an immediate change to what is shown in the right hand pane.

   

That list of class members in the right hand pane is of course the four Public Properties and three Constructors that have been created previously.

Now, in order to see the members of System.Object that the Person class inherits, click on the Object Browser Settings arrow again and this time select 'Show Inherited Members':

   


Now you will some additional items in the list of members in the right hand pane:

   

You can see the final item in that list is the ToString method of the base class. That is, the ToString method of System.Object. Left-click on 'ToString' and look at the information pane below the members list:

   

You can see that it reads:
Public Overridable Function ToString() As String
Member of System.Object

We will deal with 'Overridable' shortly, but for now note that this Public Function is a member of the System.Object class. And because Person inherits from System.Object, the Person class too has a ToString method which initially is the same as its parent's ToString method.

I am going to walk through this inheritance chain again in more detail in a moment, but before leaving the Object Browser, you should note that if you double-click any of the members of the Person class, you will immediately be taken to the code line or block of that particular member in the Person.vb file. (This doesn't apply to the members of the parent class, just Person).

System.Object.ToString
At the risk of too much repetition of the same thing, I want to run through this inheritance chain once more. I have established that the base class System.Object has a ToString method. As the following code will show, the ToString method of the System.Object parent class is configured simply to return the fully qualified name of the class . This code snippet:

Code Copy
       Dim obj As New Object
       Label1.Text = obj.ToString

will produce the following result:

   

As you can see, the System.Object.ToString method will return the Type name, which of course is "System.Object".

Now if you transfer this logic to the Person class that we created (which inherits directly from System.Object), the inherited ToString function will again return the Type name. This time though the Type name will be "ClassBasics.Person" .

   

So we've come full circle and arrived back at the unhelpful Person.ToString method. It's important that you understand how and why we get this result and I hope that the previous explanations will have clarified this for you.

Let's move on and find that way of telling the compiler that we want to replace this original version of the ToString method with a more useful method of our own. What we really want to achieve is a ToString method which will return something like:

   

 

Overridable and Overrides

Overridable and Overrides

Although Overridable and Overrides sounds quite technical, it isn't really because the meaning is just as you would use the words in normal English. That is, the one version will override or replace the settings of the original or earlier version. If something is Overridable, it can be replaced.

You are allowed to override a method in the parent class if that class has been made Overridable. Also it is important to remember that the signature of the overridden method must be the same as the signature of the parent method. ("Signature" was covered in an earlier article)

So if the parent class contains an Overridable method, then the child class may override that method. The developer of the child class has the choice as to whether to provide an overridden method or not. It is not mandatory.

The System.Object.ToString is designated as Overridable as we saw in the Object Browser :

   


Person.ToString
You can create any String you like as the returned result of the ToString method. In the case of the Person Class, the Forename and Surname are possibly the two most useful pieces of core information. So I will use these as the returned value of the ToString function - that is, what the client code gets if it calls this method.

Here is that ToString method for the Person Class:

Code Copy
    Public Overrides Function ToString() As String
        Return m_forename & " " & m_surname
    End Function

It finds the value of the m_forename and m_surname for the current instance and returns those values as a concatenated string, with a space between the two parts. Concatenated is simply developer-speak for "joined together".

Testing out this method, place the following code in the Button click event of Form1 in the ClassBasics project:

Code Copy
        ' Create a new Person Instance
        Dim RealPerson As New Person("Ged", "Mead")
        '  Display using the default ToString method
        Label1.Text = RealPerson.ToString

This time, you will get the result you want:


In this article I covered one method, ToString, in some depth. You saw that all classes inherit from System.Object and that we can override the ToString method in the System.Object class. We can do this because the declaration of the System Object's ToString method includes the Overridable modifier.

If you choose to override a method there are two key requirements:

  1. You must include the Overrides modifier in the child method declaration
  2. The signature must be the same as that of the parent method.

You can get a lot of very useful information about classes and hierarchies by using the Object Browser tool in Visual Studio.

Of course, you can include many other methods in a class - and probably would. We will look at some other methods in a later article.

In the next article in this series, I will look at Properties in more detail, how to validate values and send messages back to client code.