Article Options
Premium Sponsor
Premium Sponsor

 »  Home  »  .NET Newbie  »  Object Oriented Programming (OOP) - The Basics
 »  Home  »  Visual Studio 2008  »  Object Oriented Programming (OOP) - The Basics
Object Oriented Programming (OOP) - The Basics
by Ged Mead | Published  07/15/2009 | .NET Newbie Visual Studio 2008 | Rating:
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.

 

View all articles by Ged Mead...
Introduction, Properties and Fields

Introduction

This article will stick to the absolute basics. The aim is that by the end of the series you will be able to write a simple project of your own that uses the basic OOP principles covered here.

You'll understand enough to get started on your own and will be ready to build on these basics and get to grips with the deeper technicalities as you progress later. There's no getting away from the fact that sooner or later you are going to have to understand the more complex technical principles in order to move on. But for now we'll content ourselves with getting you started with the core, bare bones basics.

The Chess Club

We will create several classes in this tutorial, some of which will inherit from others. To try and put them in some kind of real world scenario, I will bring them all under the Chess Club umbrella. That is, all of the classes we create will be usable in a project that keeps track of some of the activities of a Chess Club.

Have a look at the diagram below:

These are the classes that we will create. Based on these classes you will be able to build a simple application to input, store and retrieve details of club members, club officials and sponsors.

The Person Class

The first class we are going to create is the Person class. As you can see from the diagram above, this class is at the top of the hierarchy. Later we will inherit from this base class, but for now we will spend some time creating its fields, properties, constructors and methods.

Start a new Windows Forms Application project. Name it "Class Basics". From the Visual Studio menu select Project: Add Class...

/>

In the dialog box which appears, enter the name of the new class: Person.vb

Click the Open button to create the Class file and have it added to the Project's file list in the Solution Explorer.

You are now ready to start adding code to this class file. The first topic we will tackle is Properties.

Understanding Properties

I remember reading the following definition of 'Property' somewhere :

    "A Property is a specific item of information about an instance created from a class. "

OK, that's fine, but what does that really mean in everyday terms?

In our project, the Person Class is meant to represent persons. Real people, that is. And because we understand the concept of what a person is in real life, we can readily accept that a Person may be described in a variety of ways.

For instance, we would happily accept that the following specific items of information might be relevant to a real person :

  • Forename
  • Surname
  • Date of Birth
  • Gender

Those, my friends, are properties - information about an instance of a Person class. It's as simple as that.

Somewhere down the line we plan to use our Person class to represent real people. We will create instances of objects from the Person Class. So it makes sense to make each of these items of information - Forename, Surname, etc - available to users of the Person class code. These will be the Properties of the Person class.

Getting and Setting Properties

When dealing with items of information - properties - we sometimes want to know the value of the item - its name, size, date, location, color, etc. Similarly there may be times when we want to assign these values ourselves - change a date, move a location, assign a name, and so on.

In the world of Properties we call these actions Getting and Setting the property values. We Get the value when we read it and we Set a property when we assign a value to it.

Property Procedures

This Getting and Setting is carried out via a specialised procedure, called a Property Procedure. There's nothing particularly magical about a Property Procedure. It's simply a function, just like many functions you have used or created yourself in the past. It optionally takes some data in, does something with it and Returns some data out.

The Property Procedure happens to have a specific form of layout. To make things easy for you, the Visual Basic editor knows what this layout should be and will create the skeleton of it for you. All you have to do is fill in the relevant details. The first property we will create is the Forename property.

The Forename Property

As is often the case, there is more than one way of bringing up the Property Procedure template. Which way you use is a matter of preference

In earlier versions of Visual Studio, the way to do this is to type in:

Property Forename as String

and then hit Enter.
A skeleton Property Procedure will then be added to the code pane for you. Go ahead and try it. You will see a code block like the following:

In Visual Studio 2008*, even more help is available, although at first it might seem more confusing than the example above. If you have tried the first example, delete it from the Person Class code, otherwise you will get an error.

Then in the Person Class type in the letters "prop" (but without the quotes) and then hit the Tab key twice. Again, you will be supplied with skeleton code. This time more colorful and containing an additional line at the top.

The first additional line creates what is known as a Field, and we will look at what that is in a moment.

In both screenshots you see that the Get and Set blocks have been created. We'll code the Getters and Setters shortly, but there are a couple of other things we need to deal with first.

If you use the second approach, you can replace those placeholder values - NewProperty and newPropertyValue. NewProperty is the placeholder name for the Property itself. You can double click anywhere on the word and replace it with the Property name we want - Forename. So the second line of the code will look like:

Public Property Forename() As String

Before we can fill in the gaps in the Property Procedure, we need to take a small sideways step to look at another class member - the Field.

Understanding Fields

Both of the Property procedures shown above create a Public Property. The second version additionally creates a Private Field.

In order for a property such as the Forename Property to be of use in any of our projects, it needs to be accessible by client code. 'Client code' or 'calling code' simply refers to code elsewhere in the project that uses this Property at some time or other. So that is why we give it Public scope. It means that the Property will be visible and accessible to code that may exist in a Form or other class elsewhere in the project.

As you will see when we come to use this property later, client code must be able to Set or Get this property - that is, it will assign or change its value (Set) or read the current value (Get).
In an ideal world, where client code always acts properly and never passes incorrect information when Setting property values, this is fine. But in the real world, the chances of client code doing something to corrupt or damage the running application is quite high and so a safety net which restricts the access is required. This safety net is the Private Field class member.

This approach enables you to hide (or encapsulate) the data inside the class. The data in this case being the value of the Forename. We allow the client code to have access to the Public properties but - tucked away inside the class itself - we keep the data secure by using a Field. A field is a private variable that is used only by the class. We can protect the field from misuse by giving it Private scope.

Private scope, as you probably already know, is not directly accessible by client code, but only by the class itself. So effectively what we do is use the Public properties as the public face of the class, but we keep the core data hidden and safe from code outside the class by storing it in a Field. The idea behind this is that if calling code can't get access to the data in the Field then it can't cause problems with it.

Some people like to think of this approach as a kind of "Black Box Technology". For instance, as a client of a bank, you are happy to use their cash dispenser. You enter your PIN and the amount of cash you want and - if your request is valid - your money will be dispensed.

You have no real idea what goes on inside the black box of the cash dispenser and you don't need to. All you need to know about it is how to insert your card and what your PIN number is. You enter the correct details and you get a result (cash). If you need to change your PIN you can do so. But you do this getting and setting of cash and PIN numbers without ever being shown what goes on inside the cash dispenser box or the system it is attached to.

Your class should be designed so that users of it - client code - can access the public face of it via Public Properties and Public Methods, but can't get behind the screen to tinker with the inner workings (The fields).

The Field

In our example, the Private Field will be named m_forename. It isn't necessary to use this naming syntax, with the m followed by the underscore, but it's traditional way of doing it. Apart from anything else, it avoids you getting confused between the name of the Property and the name of the Field.

Fields are sometimes referred to as 'backing fields', because they are used behind the publicly visible Property with which it is linked.

The m_forename field will not be accessible or visible to client code. It won't appear in the Intellisense list of options anywhere outside the code for the Person Class itself. It will only be available for use within the class.

Client code will be able to Get and Set the Forename property, but not the m_forename field. Using our cash dispenser analogy, the customer at the machine has access to the Forename, but only the bank's internal system has access to m_forename.

So, let's create our first field: m_forename. Add this line in the code window, at the top of the Class code:

    Private m_forename As String

Your class code now looks like this (VB 2005 and earlier):

Code Copy
    Private m_forename As String
    Public Property Forename() As String
        Get

        End Get
        Set(ByVal value As String)

        End Set
    End Property

Or this (VB 2008):

Code Copy
    Private m_forename As String
    Public Property Forename() As String
        Get
            Return newPropertyValue
        End Get
        Set(ByVal value As String)
            newPropertyValue = value
        End Set
    End Property

What we will do next is somehow link together the Private m_forename field and the Public Forename property. To create that link we will now add some code to the Get and Set blocks of the Forename Property Procedure.

Code for the Get Sub Block

Still in the code window for the Person Class, insert this line in the Get Sub Block of the Forename Property:

        Return m_forename

So the Get part of the Property Procedure now looks like this:

Code Copy
    Public Property Forename() As String
        Get
            Return m_forename
        End Get

What does this line of code actually do? It provides a way for the client code to obtain the value that is stored for the m_forename field for a particular Person instance.

I know I keep emphasizing this, but it is important to understand that the property doesn't let the client code have direct access to the m_forename field itself. It only tells the client code what value is currently held in m_forename via the Forename property, which is Public. It's a subtle but important difference.

Code for the Set Sub Block

Now put the following code in the Set sub block:

        m_forename = Value

The Property Procedure now looks like this:

Code Copy
    Public Property Forename() As String
        Get
            Return m_forename
        End Get
        Set(ByVal value As String)
            m_forename = value
        End Set
    End Property

The code in the Set sub block works in the opposite way to Get. It indirectly allows client code to change the value of the m_forename field. The key word to note again is indirectly. The client code actually only interacts directly with the public Property Forename; the value is then passed internally to the m_forename field.

As before, if you think of this exchange of information as the cash dispenser example then it should become clear why this code is used. The client can change (Set) the Forename Property and then this value will be passed internally to the m_forename field.

In many cases, the Property procedure will be no more complicated than the one shown above. It keeps the core data safe, but still allows client code to access the values of Properties directly and Fields indirectly.

I should mention in passing that you can include validation in the Get and Set sub-blocks. For example, you may not want to allow a Forename of more than, say, 15 characters. In this kind of case, you insert an If statement in the Set block which will only allow the Forename to be set if it is less than the allowed length. Validation can be more complex than this, but that is a typical example of its use.

Default Value of a Field

At this stage I want to make a small but important change to the declaration of m_forename. I am going to recommend that you amend that so that it reads:

    Private m_forename As String = "No Forename"

Why? The reason is that the first version will create the m_forename field and it will have a default value of "" - that is, an empty string. (It's not "nothing", by the way; it is a string that happens to contain no characters.)

This may not cause a problem most of the time. However, there may come a time when you try to display the forename of a person and, when no text appears, the user may become confused.

In fact, while you are creating the project and debugging, you may even forget about this possibility yourself and start searching for a "missing" field which isn't actually missing.

So assigning a default value is a good habit to adopt. It takes minimum effort and may save you a headache or two later.

Adding More Properties and Fields

The Person Class currently contains one field and one property. If you remember in the Introduction, I talked about items of information (properties) that would be appropriate for a Person. These were:

  • Forename
  • Surname
  • Date of Birth
  • Gender

What I will do now is to create those additional three properties, together with three fields.

The properties will be as follows:

  • Surname : String.
  • DateOfBirth : (Note that there are no spaces between words) Date
  • Gender : String.

The fields will be:

  • m_surname: String, Default value = "Anonymous"
  • m_dateofbirth: Date, Default Value = #1900, 1, 1#.
  • m_gender: String, Default value = "Not Known"

So, the Class at this stage will look like this:

Code Copy
Public Class Person

    Private m_forename As String = "No Forename"
    Public Property Forename() As String
        Get
            Return m_forename
        End Get
        Set(ByVal value As String)
            m_forename = value
        End Set
    End Property

    Private m_surname As String = "Anonymous"
    Public Property Surname() As String
        Get
            Return m_surname
        End Get
        Set(ByVal value As String)
            m_surname = value
        End Set
    End Property

    Private m_dateofbirth As Date = #1/1/1900#
    Public Property DateOfBirth() As Date
        Get
            Return m_dateofbirth
        End Get
        Set(ByVal value As Date)
            m_dateofbirth = value
        End Set
    End Property

    Private m_gender As String
    Public Property Gender() As String
        Get
            Return m_gender
        End Get
        Set(ByVal value As String)
            m_gender = value
        End Set
    End Property

End
Class

I hope this explanation of Properties and Fields clarifies any confusion about what they are and why we use them. In the next part of this article, we will look at Constructors - a means of creating new instances of Person objects.


* And just to confuse things even more, when VB 2010 becomes available, there will be yet another option, but we'll leave that until the day arrives.

How would you rate the quality of this article?
1 2 3 4 5
Poor Excellent
Tell us why you rated this way (optional):

Article Rating
The average rating is: No-one else has rated this article yet.

Article rating:3.66037735849056 out of 5
 53 people have rated this page
Article Score9806
Sponsored Links