Creating Classes and other Web Objects in .NET


VB.NET is an Object Oriented programming language. The Objects referred to are created from something called a Class. You’ve already used Classes throughout this course. But we’ll now have a closer look at them.

Object Oriented programming


oopThe modern trend in programming languages is for code to be separated into chunks. When it’s being used, each chunk of code (a chunk of code that opens text files, for example) is known as an Object. The code for the Object can then be reused whenever it is needed. Languages like C++ and Java are Object Oriented languages. Until Microsoft came out with VB.NET, the Visual Basic programming language was not OOP (object oriented programming). This time it is.

Object Oriented programming has a steeper learning curve, and things like Encapsulation, Inheritance and Polymorphism have to be digested. We’re not going quite that far in this beginner’s course. But you should have a good, basic understanding of just what Object are by the end of this section, and how to create your own Objects.

Classes and Objects


In VB.NET, a class is that chunk of code mentioned earlier. You’ve been using Classes all the time during this course. The Form you’ve started out with is a Class. If you look right at the top of the code window, you’ll see:


Public Class _Default
    Inherits System.Web.UI.Page

The word “Public” means that other code can see it. _Default is the name of the Class.

If you look at the bottom of the coding window, you’ll see End Class, signifying the end of the code for the Class.

When you place a Button or a textbox on the Form, you’re really adding it to the Form Class.

When you start the Form, VB does something called instantiation.

This basically means that your Form is being turned into an Object, and all the things needed for the creation of the Form are being set up for you (Your controls are being added, variables are being set up an initialised, etc).

And that’s the basic difference between a Class and an Object: A Class is the code itself; the code becomes an Object when you start using it.

The NET Framework


The NET Framework is something that Microsoft have invested a lot of time, effort and money into creating. It’s big. Very big.

The way that programming will be done on a Microsoft machine from now on is with NET. And not just on a Microsoft machine. There’s something called ADO.NET which is used for creating web site, and for manipulating databases. You can create applications for mobile phones and PDA’s with NET. There is even a project in the making that will allow you to write a program on a Windows machine that will then work on a computer NOT running Windows. All this is made possible with the NET Framework. But what is it?

The NET Framework is a whole lot of Classes (called Namespaces) and the technology to get those Classes to work. The main component is called the Common Language Runtime. A Runtime is the thing that gets your code to actually run on a computer. Previously, these Runtime Languages were machine or programming language specific. The Runtime that gets a Java program to work, for example, is different to the one that gets a C program to work. With NET, more than 15 different programming languages can use the Common Language Runtime. One of these languages is, of course Visual Basic NET. Another is C# (pronounce C Sharp). They can all use the Common Language Runtime because of something called the Intermediate Language. (This is a sort of translator for the various languages, and is too advanced to go into for us.)

Namespaces


A Namespace is a group of Classes which are grouped together. The System.IO Namespace you met earlier groups together Classes that you use to read and write to a file. System.Windows.Forms is another Namespace you’ve met. In fact, you couldn’t create your forms without this Namespace. But again, it is just a group of Classes huddling under the same umbrella.

System itself is a Namespace. It’s a top-level Namespace. Think of it as the leader of a hierarchy.

IO and Data would be part of this hierarchy, just underneath the leader.
Each subsequent group of Classes is subordinate to the one the came before it.

For example:

Imports System.Data
Imports System.Data.SqlClient

This means that the Data Namespace is loaded from the System Namespace. The SQlClient is a sub-class and it will be loaded from the Data Namespace which will be loaded from the System Namespace.

The dot notation is used to separate each group of Classes.

The leader of the hierarchy is still System, though. Think of it as an army.

You’d have a Private who is subordinate to a Sergeant.

The Sergeant would be subordinate to a Captain. And the Captain would be subordinate to a General.

If the General wanted something done, he might ask the Captain to do it for him. The Captain would get the Sergeant to do it, and the Sergeant would then pick on a poor Private.

So a Button would be the Private, Forms would be the Sergeant, Page would be the Captain, and System the General.

You will see this chain of command every time you type a full stop and a pop up box appears. When you’re selecting an item from the list,
you’re selecting the next in the chain of command.

 

Make your own Controls, Classes and Namespaces


The big benefit of an Object Oriented Programming language is that you can create your own Objects. (It’s an Object when you’re using the code, remember, and a Class when you’re not.)

We’ll see how to do that now, as we create a very simple Class, and then turn that into an Object.

The Class we’ll create is a very simple one, and is intended to show you the basic technique of setting up a Class, then creating an object from it. The Class we’ll create will convert the letters in a postcode to uppercase. We’ll get the postcode from a textbox on a form. Off we go then.

Start a new VB .NET project

Add a Textbox to your form, and name it txtPerson

Add a Textbox to your form, and name it txtAge

Add a Button to your form and name it btnCalculate

Once you have a new form, you need to add a Class. This is quite easy.

Right click on Project, chose Add>new item and then browse for class. Name your class Person.vb

A new page will open with the following contents:

Public Class Person

End Class

 

Properties and Methods


A class is like a car. It has properties (like colour, engine size, owner) and it has a set of actions it can do, called methods (like StartEngine, StopEngine, RunHome).

You can declare your properties using snippets (they are pre-defined pieces of code that will simplify your coding time)

To do so, right click on the blank form and choose Insert Snippet>Double click on Code Patterns>Properties, Procedures, Events. And then select Define a Property

iSnippet

iprop

As you can see there are many options available, based on what you are looking to achieve. A Read-Only Property can read but not written to.

You will now create a property called “Name”
iname
Name your private variables with an underscore and all your public ones with Capitalisation (first letter uppercase).

Declare another property called “Age” as Integer. You can easily tab through the highlited fields and changing one will change all of them.

Now we will add a method which will check whether the person is underage or not.

To define a function (which returns a result), you will use the keyword “function”. To define a procedure (which does only work and returns no result), you will use the keyword “Sub”.

        Public Function IsMinor() As Boolean
            If _age < 18 Then
                Return True
            Else
                Return False
            End If
        End Function
  • Public will make the function visible from wherever we call it.
  • Function says that we will be returning a result
  • IsMinor – function name
  • As Boolean – return type (can be any of the types defined before)
  • If … Then .. Else .. End If — this structure will validate a condition. If the condition is true, the “Then” part will be execute, otherwise the else part. End if marks the end of the statement.
  • _ageValid operators are: < (less than); > (greater than); = (equal to); <> (different); >= (greater or equal to); <= (less than or equal to)
  • Return – each function needs to have a “Return” statement where the value is sent back to the caller.
  • True/False – possible values for a Boolean result.

 

Using a class


The usage of the class is called “instantiation” – it’s when the code becomes an Object.

Dim p As New Person 'instantiate a new Person
        p.Name = txtPerson.Text 'assign the name of the person, we are using the "Set" in the property
        p.Age = txtAge.Text
        If p.IsMinor Then
            lblResult.Text = p.Name & " is minor!"      ''we are using the "Get" in the property
        Else
            lblResult.Text = p.Name & " can drink beer!"
        End If

If you would like to skip two lines of code, you can assign the name and age of the person when the object is creating by overriding the “New” method. This is called when the object is first created and can be used to populate the inner properties.

To do this, in the class, drop down the right drop-down and chose new.

inew
          Public Sub New()


will be added to the class. Copy this function and then modify the copy like in the image below:
inew2

This means that a new “Person” object can be created without parameters or with the Name and Age as parameters.

If they are specified, they will be assigned to the person details. If we look now back in the default function, we shall erase / comment out the part we have just done and put in the new code.
When you start typing the person object instantiation, you will see that all of a sudden, you have two option when you declare it (see below)

inew3

inew4

This is it! Run the project (F5) and press the button to see what you get.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s