Article Options
Premium Sponsor
Premium Sponsor

 »  Home  »  .NET Newbie  »  OOP: Create, Collect, Sort, Save and Retrieve Objects
 »  Home  »  Visual Studio 2005  »  OOP: Create, Collect, Sort, Save and Retrieve Objects
 »  Home  »  Windows Development  »  Visual Basic 2005  »  OOP: Create, Collect, Sort, Save and Retrieve Objects
OOP: Create, Collect, Sort, Save and Retrieve Objects
by Ged Mead | Published  03/18/2007 | .NET Newbie Visual Studio 2005 Visual Basic 2005 | 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...
The Player Class

   The first thing we are going to do is to build a very simple Player class. Using this class we will be able to create individual Player objects (or Instances of the Player Type ).

Getting Started

   I have used the Visual Basic 2005 Express Edition of Visual Studio 2005 for all the screenshots and code demonstrations. If you use a different version, some of the screens will be slightly different, but not enough to cause you any major problems.

   Create a new project if you want to build the code as we work through the article. Select Windows Application as the project type. I have named my version "PlayerDemo".

  By default, there will be a Form named Form1 in the Solution Explorer pane. We will use this later, but first I want to create the basic Player Class. So, to do this, in the IDE main menu select Project > Add Class:

To rename this new class, type in "Player.vb" and press Enter.

Initial Class Code

  This article is aimed at relative newbies, but that's a description that spreads across a lot of different learning levels.   If you have created classes already, the following description will be easy for you to follow.  However, if you are a total beginner and are already wondering what it's all about then you may be interested in learning the basics of classes by participating in the VBCity Academy OOP1 course. This online course is cost free to VBCity Members and is available from the VBCity Academy. Further details, including upcoming course dates, are announced in the Academy Forum.

   As I described on the previous page, this class is designed to keep track of players in a game, together with their scores. So we need to have properties for both Name and Score.   In order to create new players we have to include a constructor (Sub New).   You'll be very familiar with the "New" keyword and will have used it many times,  e.g. 

Dim alMYPictures As New ArrayList

Dim MyPic As New Bitmap("Mugshot.bmp")

   and so on.   But if you haven't created your own classes before, you may not know that this is the code that allows us to create new objects by using the New keyword .

  So in this article we will create a constructor for the class.   In fact, for convenience, we will also create a second version of the Player constructor (usually referred to as an overloaded version).  This isn't strictly necessary, but it will allow us to create Player objects and assign a Name and a Score at the same time - similar to the Bitmap example above, which allows us to pass in the name of the new bitmap when it is created.  The text in the brackets above is known as a parameter.

  Also for convenience, the class will have a ToString method. You will probably be familiar with this method because the .NET Framework Types all have a ToString method that you can select from the Intellisense list.   What it actually does is that it returns a string representation of the object - or in plain English -  some text that will be meaningful to users. 

   Finally, although this is a very simple class, we should still follow recommended OOP principles and use Private fields to hold the data that is assigned to the Name and Score properties.   In very general terms,  these Private fields shield the important data by storing it safely inside the class itself.  Code that accesses the class cannot access or change the values inside those fields directly; this must be done via the Name and Score Properties described above.

So, in summary, the Player Class will include :

  • two Properties - Name and Score,
  • two backing Fields for those properties - m_Name and m_Score,
  • a Default Constructor and an Overloaded Constructor
  • a ToString method


   Although we will make some changes later, here is the first pass at our code for the Player Class:

Public Class Player

' Two Fields
Private m_Name As String
Private m_Score As Integer

' Two Properties
Public Property Score() As Integer
   Return m_Score
  End Get
  Set(ByVal Value As Integer)
   m_Score = Value
  End Set
End Property

Public Property Name() As String
  Return m_Name
  End Get
  Set(ByVal Value As String)
   m_Name = Value
  End Set
End Property

' Two Constructors
Public Sub New()
End Sub

Public Sub New(ByVal playerName As String, ByVal playerScore As String)
   Name = playerName
   Score = playerScore
End Sub

' ToString method
Public Overrides Function ToString() As String
  Return m_Name
End Function

End Class

Creating Player Objects
   We'll set up some controls on that Form1 so we can create new Player instances and assign values to their properties. The screenshot below shows the layout I've used. A couple of TextBoxes, a Button and a Label to display the result.

With the following code in the Button Click event, we can test the class:

  Dim Player1 As New Player(TextBox1.Text, CInt(TextBox2.Text))

   Label3.Text = String.Format("Player Name: {0} {1}Current Score: {2}", Player1.Name, ControlChars.CrLf, Player1.Score.ToString)

  The first line creates a new Player object and assigns what it finds in TextBox1 as the Name and what it finds in TextBox2 as the Score.  

   The remaining lines (actually it is all one line, but may be too long to fit on screen, depending on your monitor resolution):  This takes the values that we have assigned to the Player object and displays them in a particular format so that we can see that the class code works properly.   I know that the String.Format syntax looks a bit weird if you haven't seen it before, but it actually is a big help when you want to create complex strings that pull information in from all over the place.  If you find the above confusing then you can think of it like this:

  Label3.Text = "Player Name: "

  Label3.Text &= Player1.Name

  Label3.Text &= ControlChars.CrLf

  Label3.Text &= "Current Score: "

  Label3.Text &= Player1.Score.ToString

    Once you have created this first part of the project, have a play with it, changing the Name and the Score a couple of times.  

   One thing you will probably quickly find out is that it doesn't take much to crash the project as it stands.  That's mainly because we are trusting the user to enter valid Names and Scores in those TextBoxes; an assumption that is never safe to make, even when the user is you!

  Later we will come back and make some changes to the class, but it is sufficient for our needs for now and we can look at how to create a collection of Players as I mentioned in the introduction.

Sponsored Links