.Net Programming - Financial independence

Classes and Object Oriented Programming in Visual Basic/C#

This is the mother of all tutorials, it is not important, it is really important! Classes are an essential part of object oriented programming and if you wish to continue on, you should really pay attention to this one.

Objects

Nearly everything is an object in Visual Basic/C#. In fact, without even knowing it we’ve used them a lot in the last few tutorials. Let’s say that Visual Basic/C# is a way to work, objects (classes) are tools and the .Net Framework is our (big) toolbox. What is the .Net Framework? It’s the collection of tools that Microsoft provides to help us save a lot of time by not reinventing the wheel every time we code. Code reuse is one big advantage of object oriented programming!

Now remember that almost everything is an object in these two programming languages.

Classes

Classes are technically blueprints of objects, like plans for a plane for example. It’s how to build it, but not the physical thing. You should keep that in mind when we will create our first class in a few lines!

A class can contain a few things:
– Constructors
– Parameters
– Members
– Methods
– Inherited methods and parameters (like ToString())

All these elements might not be familiar, that’s why we’re going to explore them one by one briefly in this tutorial.

We’re going to create a new class first and have a look at the structure.

1. Create a new Console project and right click on the project in the Solution Explorer

2. Hover on Add -> click on new Item.

3. Select Class and give it the name: Car.

Visual Basic

Car class

C#

CSharp new item

It should give you the following code representing an empty class.

Visual Basic

Public Class Car

End Class

C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ClassesCSharp
{
    public class Car
    {

    }
}

This will act as our car blueprint. In other words, if we want to make real cars, we’re going to have to use this blueprint!

Constructor

A constructor defines the way to initially build the object from the blueprint. There can be multiple constructors possible for one class but all will serve the same purpose. It’s important to remember that the constructor is a bit special in a way that it will be executed before anything else in the class just after the real object is created. Also, it doesn’t have a return value like other methods and has the name of the class itself (in Visual Basic it’s going to have the name New). Here is the base structure of our Car class constructor:

Visual Basic

Public Class Car
    'Constructor
    Public Sub New()

    End Sub
End Class

C#

namespace ClassesCSharp
{
    public class Car
    {
        //Constructor
        public Car()
        {

        }
    }
}

We will not put anything in the constructor for now.

Parameters

The parameters are variables accessible outside of the class. Yes, a class is sort of like a box where some things are accessible from the outside and some things aren’t. Think of a drill for example, you can access that button to start drilling and the forward and backward buttons, but you cannot access the mechanism inside the drill, still, you have some information like the voltage, drilling speed and so on. This information is like the parameters. It gives you information about the class itself that you can or cannot modify.

For our example, we’re going to add the IsStarted and PaintColor parameters. Remember that the Parameters are states, not actions. For parameters that can be read, we’re going to use the Get keyword, and for parameters that can be modified, we’re going to use the Set keyword. It’s logical, you can get a value and/or set a value. Here is the corresponding code:

Visual Basic

Public Class Car
    'Members
    Private _PaintColor As String
    Private _IsStarted As Boolean

    'Parameters (Properties)
    Public Property PaintColor As String
        Get
            Return _PaintColor
        End Get
        Set(value As String)
            _PaintColor = value
        End Set
    End Property
    Public Property IsStarted As Boolean
        Get
            Return _IsStarted
        End Get
    End Property

    'Constructor
    Public Sub New()

    End Sub
End Class

C#

namespace ClassesCSharp
{
    public class Car
    {
        //Members
        private string _PaintColor;

        public string PaintColor
        {
            get
            {
                return _PaintColor;
            }
            set
            {
                _PaintColor = value;
            }
        }
        public bool IsStarted { get; private set; }

        //Constructor
        public Car()
        {

        }
    }
}

Where all this code comes from you say? There are in fact a lot of modifiers and a lot of different ways to implement Parameters (or Properties in Visual Basic). We’re going to divide all the code into smaller parts.

First, the Members section describes private variables (not accessible outside the class) that will be used with the parameters. In fact, the parameters will only be the way to access these values from outside if applicable. Here we have two parameters and one member associated with PaintColor (two in Visual Basic).

PaintColor can be retrieved and set from outside, that’s why it has a Public Parameter with a Getter and a Setter. The Get simply returns the value that is contained in the class and the Set sets the value passed by the user of the class to assign it to the _PaintColor member. If you have difficulty to see the difference between the parameter and the member, you can tell yourself that the parameter is more of a regulated door to access a variable which is the member.

There are two ways of writing Properties, the long way and the short way but they give the exact same result:

Visual Basic – Long version

    Private _PaintColor As String

    Public Property PaintColor As String
        Get
            Return _PaintColor
        End Get
        Set(value As String)
            _PaintColor = value
        End Set
    End Property

C# – Long version

        private string _PaintColor;

        public string PaintColor
        {
            get
            {
                return _PaintColor;
            }
            set
            {
                _PaintColor = value;
            }
        }

In the long version, we declare an associated private variable that we return and set during the Parameter (Property) retrieval or assignment.

Visual Basic – Short version

Public Property PaintColor As String

C# – Short version

public string PaintColor { get; set; }

The down side of the short version is that you cannot declare a body if you want to validate inputs or output or even return a value that does some processing before being returned. You will have to use the long version to accomplish this task.

Remark: the parameter must be of the same type as the variable it encapsulates, in our case, PaintColor is of type string and _PaintColor is also of type string.

Our final shortened version is now:

Visual Basic

Public Class Car
    'Parameters (Properties)
    Public Property PaintColor As String
    Public Property IsStarted As Boolean

    'Constructor
    Public Sub New()

    End Sub
End Class

C#

namespace ClassesCSharp
{
    public class Car
    {
        //Parameters
        public string PaintColor { get; set; }
        public bool IsStarted { get; private set; }

        //Constructor
        public Car()
        {

        }
    }
}

You can see that I don’t even need members now because the variable is implicitly handled in the back end.

To summarize the parameter theory, If you want to add validation or a particular case, you will have to use the long version of parameters (Properties in Visual Basic). The private get/private set can be used to shortened the parameter declaration and implicitly declare a private variable. Finally, a parameter is like a characteristic, therefore, its name should not be an action. Instead it should be a state, for example: IsActive, PaintColor, IsStarted, TopSpeed and so on.

Let’s test this out!

We want to make sure that Visual Basic/C# can see our parameters. For that, we will have to create what we call an instance of the class(blueprint) we just created! This will create a real object of type Car in memory.

Here is how to proceed:

1. Go back into the Main Sub in Program.vb/Program.cs Main() function

2. Declare a new Variable with name MyCar (or whatever you like) as type Car.

Visual Basic

Visual Basic Car declaration and initialization

C#

C Sharp Declaration

Why the ()? That’s because we are using the constructor here creating a new instance of the class Car.

You should be able to see both parameters when entering the name of the variable and “.”.

Visual Basic

Visual Basic Car intellisense

C#

CSharp intellisense

Members

Members normally cannot be seen from outside and will remain private. They are class specific variables to help in whatever processing that is going on in that class.

For example, a list of passengers that doesn’t need to be accessed in any way by the user of the object.

Visual Basic

Public Class Car
    'Members
    Private _Passengers As List(Of String)

    'Parameters (Properties)
    Public Property PaintColor As String
    Public ReadOnly Property IsStarted As Boolean

    'Constructor
    Public Sub New()

    End Sub
End Class

C#

namespace ClassesCSharp
{
    public class Car
    {
        //Members
        private List _Passengers;

        //Parameters
        public string PaintColor { get; set; }
        public bool IsStarted { get; private set; }

        //Constructor
        public Car()
        {

        }
    }
}

Methods

Methods are useful to accomplish actions on the object. In fact, methods should be named after actions, for example: Start, Stop, IncrementMileage and so on. They can be Sub(Visual Basic) and/or functions (C# and Visual Basic).

Visual Basic

    Public Sub StartEngine()
        'Check if engine is started first!
        If Not IsStarted Then
            IsStarted = True
        End If
    End Sub

C#

        public void StartEngine()
        {
            if (!IsStarted)
                IsStarted = true;
        }

In this example you can see that I am using a standard Sub(Visual Basic)/function(C#) so nothing is different, a function is like a method, in fact it is pretty much the same thing!

Let’s add the StopEngine Sub/function to our class as well. Here is what it gives us!

Visual Basic

Public Class Car
    'Members
    Private _IsStarted = False
    Private _Passengers As List(Of String)

    'Parameters (Properties)
    Public Property PaintColor As String
    Public Property IsStarted As Boolean
        Get
            Return _IsStarted
        End Get
        Private Set(value As Boolean)
            _IsStarted = value
        End Set
    End Property

    'Constructor
    Public Sub New()
        '_Passengers will be Nothing at that point, the constructor is our chance to initialize it!
        _Passengers = New List(Of String)
    End Sub

    Public Sub StartEngine()
        'Check if engine is started first!
        If Not IsStarted Then
            IsStarted = True
        End If
    End Sub

    Public Sub StopEngine()
        'Check if engine is started first!
        If IsStarted Then
            IsStarted = False
        End If
    End Sub
End Class

C#

using System.Collections.Generic;

namespace ClassesCSharp
{
    public class Car
    {
        //Members
        private List _Passengers;

        //Parameters
        public string PaintColor { get; set; }
        public bool IsStarted { get; private set; }

        //Constructor
        public Car()
        {
            //_Passengers will be Null at that point, the constructor is our chance to initialize it!
            _Passengers = new List();
        }

        public void StartEngine()
        {
            //Check if engine is started first!
            if (!IsStarted)
                IsStarted = true;
        }

        public void StopEngine()
        {
            //Check if engine is started first!
            if (IsStarted)
                IsStarted = false;
        }
    }
}

What happened to the constructor here!? I added the initialization of the passengers list and yes, a constructor works just like a method and is a place of choice to initialize the members and parameters! Don’t forget that in Visual Basic, a constructor is named New and in C#, you have to use the name of the class as the method name.

Predefined methods

Some methods are predefined when you create a new class (blueprint), they actually come from the object itself, Object is sort of the Master class that every other classes inherit from (we will explore this topic in the next few tutorials). One of the method is ToString(). The ToString method is a String representation of the current object, you can implement your own ToString method in the class you just created if you want.

Instances

A class is like a blueprint, it’s a way of building an object. You can build multiple instances of an object if you want, all the instances will be different, just like every car is the same when it’s out of the factory but will change during its usage. Here is an example of such behavior.

Visual Basic

Visual Basic Car instances

C#

C# Instances

As you can see, the two instances created in this code are separated, if I modify one of them, the other instance is not impacted by the changes. The output shows that the value of IsStarted of the first car is false because it is distinct from the second car that has been started and has a IsStarted value of true.

Complete Code

Here is the complete code for this tutorial.

Program.vb/Program.cs

Visual Basic

Module Program
    Sub Main()
        'Creating two instances of a Car object
        Dim MyCar As New Car()
        Dim SecondCar As New Car()

        'Starting the second car engine to show that both car are now separate instances
        SecondCar.StartEngine()
        Console.WriteLine("First car status: " & MyCar.IsStarted)
        Console.WriteLine("Second car status: " & SecondCar.IsStarted)

        Console.ReadKey()
    End Sub
End Module

C#

using System;

namespace ClassesCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            Car MyCar = new Car();
            Car SecondCar = new Car();

            //Starting the second car engine to show that both car are now separate instances
            SecondCar.StartEngine();
            Console.WriteLine("First car status: " + MyCar.IsStarted);
            Console.WriteLine("Second car status: " + SecondCar.IsStarted);

            Console.ReadKey();
        }
    }
}

Car.vb/Car.cs

Visual Basic

Public Class Car
    'Members
    Private _IsStarted = False
    Private _Passengers As List(Of String)

    'Parameters (Properties)
    Public Property PaintColor As String
    Public Property IsStarted As Boolean
        Get
            Return _IsStarted
        End Get
        Private Set(value As Boolean)
            _IsStarted = value
        End Set
    End Property

    'Constructor
    Public Sub New()
        '_Passengers will be Nothing at that point, the constructor is our chance to initialize it!
        _Passengers = New List(Of String)
    End Sub

    Public Sub StartEngine()
        'Check if engine is started first!
        If Not IsStarted Then
            IsStarted = True
        End If
    End Sub

    Public Sub StopEngine()
        'Check if engine is started first
        If IsStarted Then
            IsStarted = False
        End If
    End Sub

    Public Overrides Function ToString() As String
        Return MyBase.ToString()
    End Function
End Class

C#

using System.Collections.Generic;

namespace ClassesCSharp
{
    public class Car
    {
        //Members
        private List _Passengers;

        //Parameters
        public string PaintColor { get; set; }
        public bool IsStarted { get; private set; }

        //Constructor
        public Car()
        {
            //_Passengers will be Null at that point, the constructor is our chance to initialize it!
            _Passengers = new List();
        }

        public void StartEngine()
        {
            //Check if engine is started first!
            if (!IsStarted)
                IsStarted = true;
        }

        public void StopEngine()
        {
            //Check if engine is started first!
            if (IsStarted)
                IsStarted = false;
        }
    }
}

Conclusion

Again, classes take an important part in object oriented programming, I would say that they are the core of it essentially. If you’re not sure about a concept learned in this tutorial, I strongly suggest that you watch the video and post your questions here or on Youtube! This is only the first part on the subject, in the next tutorial we’re going to dive a bit deeper into object oriented programming and classes. Don’t give up!

External References

Here is a link to the MSDN library for more details on classes.

Visual Basic

C#

Next article How Class Constructors Work in C#/Visual Basic
Previous article Collections.Generic in Visual Basic/C# - Exercise and Solution

Related posts

0 Comments

No Comments Yet!

You can be first to comment this post!

Leave a Comment

Your data will be safe! Your e-mail address will not be published. Also other data will not be shared with third person. Required fields marked as *