.Net application development specialists
asp.net, c#, vb.net, html, javascript, jquery, html, xhtml, css, oop, design patterns, sql server, mvc and much more
contact: admin@paxium.co.uk

Paxium is the company owned by myself, Dave Amour and used for providing IT contract development services including


  • Application development - Desktop, Web, Services - with Classic ASP, Asp.net WebForms, Asp.net MVC, Asp.net Core
  • Html, Css, JavaScript, jQuery, React, C#, SQL Server, Ado.net, Entity Framework, NHibernate, TDD, WebApi, GIT, IIS
  • Database schema design, implementation & ETL activities
  • Website design and hosting including email hosting
  • Training - typically one to one sessions
  • Reverse Engineering and documentation of undocumented systems
  • Code Reviews
  • Performance Tuning
  • Located in Cannock, Staffordshire
Rugeley Chess Club Buying Butler Cuckooland Katmaid Pet Sitting Services Roland Garros 60 60 Golf cement Technical Conformity Goofy MaggieBears Vacc Track Find Your Smart Phone eBate Taylors Poultry Services Lafarge Rebates System Codemasters Grid Game eBate DOFF

Constructors in C# And Vb.net

The main research for which the findings of this article are based were done by creating a collection of simple console applications covering all the constructor scenarios I could think of.

These scenarios and their output results when executed can be found at the end of this article.

When you create an instance of a class in either C# or Vb.net then a method or subroutine is automatically called when we do so.  This special method or sub routine allows us to perform a number of functions.  Firstly it allows us to run any code which is needed to initialise anything within that class instance.  Secondly it allows us to pass in values to the call to create an object so that instantiaton and initialisation can be done all in one eg we can do:

Person fred = new Person("Fred", "Bloggs", 100);

rather than

Person fred = new Person();

fred.Firstname = "Fred";
fred.Firstname = "Bloggs";
fred.Money = 100;

With the advent of object initialisers as below, then you may think that this makes such overloaded constructors obsolete but don't forget that the constructor method can have complex logic in there rather than just assigning values passed in to object members.

Example C# Object Initializer

GamePlayer tracey = new GamePlayer { Health = 200, PlayerName = "Tracey" };

Example Vb.net Object Initializer

Dim tracey As New GamePlayer() With {.Health = 200, .PlayerName = "Tracey"}

A subtle part of constructors of any kind is that if we have properties or fields then unless we explicitly set these then the constructor will give them their default values - eg zero for an int.   If you declare an int in C# as a local variable and then try and use it when it has not been assigned a value then this will not compile (Note that VB.net does initialise varaibles with their default values).  With objects though the constructor whether it be a default one or an overloaded one will give default values to all fields and properties which we do not explicitly set.

Because a constructor is a method or sub routine then its access can be limited with access modifiers - eg public, private etc.  Exploiting this is a way to realise a singleton design pattern in .net languages.  This is beyond the scope of this article though.

When creating a constructor in C# we create a method with no return type whose name is the same as the class name.  In Vb.net we create a sub routine which always has the same predefined name.  The name of this sub routine is New.  Code samples for these are as follows.  The scenario in question could be something like a poker game where new players have to have a certain amount of money initialised.

C# Example Constructor

public class Person
{
    public Decimal Money { get; set; }
    public string Firstname { get; set; }
    public string Surname { get; set; }

    public string SayHello()
    {
        return String.Format("Hello my name is {0} {1}. I have £{2} and am ready to play", Firstname, Surname, Money);
    }

    public Person()
    {
        Money = 100;
    }
}

Example Constructor

Public Class Person

    Public Sub New()
        Money = 100
    End Sub

    Public Property Money As Decimal
    Public Property Firstname As String
    Public Property Surname As String

    Public Function SayHello() As String
        Return String.Format("Hello my name is {0} {1}. I have £{2} and am ready to play", Firstname, Surname, Money)
    End Function
End Class

As with other methods(C#) and sub routines(Vb.net) we can have overloads as follows (The overloads are highlighted in yellow):

C# Example Overload

public class Person
{
   public Decimal Money { get; set; }
   public string Firstname { get; set; }
   public string Surname { get; set; }

   public string SayHello()
   {
       return String.Format("Hello my name is {0} {1}. I have £{2} and am ready to play", Firstname, Surname, Money);
   }

   public Person()
   {
       Money = 100;
   }

   public Person(string firstname, string surname, Decimal money)
   {
       this.Firstname = firstname;
       this.Surname = surname;
       this.Money = money;       
   }
}

Vb.net Example Overload

Public Class Person
    Public Sub New()
        Money = 100
    End Sub

    Public Sub New(Firstname As String, Surname As String, Money As Decimal)
        Me.Firstname = Firstname
        Me.Surname = Surname
        Me.Money = Money
    End Sub

    Public Property Money As Decimal
    Public Property Firstname As String
    Public Property Surname As String

    Public Function SayHello() As String
        Return String.Format("Hello my name is {0} {1}. I have £{2} and am ready to play", Firstname, Surname, Money)
    End Function
End Class

Note that if we create a simple class and write no constructor at all then a default one will be created for us under the hood.  This doesn't appear to be of much significance until we try doing something like the following:

using System;

namespace Constructors.UI
{
    public class Program
    {
        static void Main(string[] args)
        {
            Person sarah = new Person("Sarah", "Smith", 100);

            Person fred = new Person();

            Console.ReadKey();
        }
    }

    public class Person
    {
        public Decimal Money { get; set; }
        public string Firstname { get; set; }
        public string Surname { get; set; }

        public Person(string firstname, string surname, Decimal money)
        {
            this.Firstname = firstname;
            this.Surname = surname;
            this.Money = money;

            Money = 100;
        }
    }
}

What will happen here is that this will not compile.  The C# error message you will encounter will be "Constructors.UI.Person does not contain a constructor that takes 0 arguments" - Thre Vb.net error message will be worded differently but will mean the same thing.  So what is clearly happening here is that we only get a default constructor automatically when we create no other constructors.  If we have created other constructors then we don't get the default one automatically and we have to write it ourselves.  At the very least we would need the following code in order for this to compile:

    public class Person
    {
        public Decimal Money { get; set; }
        public string Firstname { get; set; }
        public string Surname { get; set; }

        public Person()
        {

        }

        public Person(string firstname, string surname, Decimal money)
        {
            this.Firstname = firstname;
            this.Surname = surname;
            this.Money = money;

            Money = 100;
        }
    }

Note that you only need to do this only if you attempt to create an instance of a class with the default constructor, if you don't then you can get away without it!

Another important area of study where constructors are concerned is that of inheritance.

Consider the following code:

using System;

namespace Constructors.UI
{
    public class Program
    {
        static void Main(string[] args)
        {
            Tank m1Abrams = new Tank();

            m1Abrams.ShellSize = 100;

            Console.WriteLine("Shellsize {0}, Colour: {1}", m1Abrams.ShellSize, m1Abrams.Colour);

            Console.ReadKey();
        }
    }

    public class Vehicle
    {
        public int Wheels { get; set; }
        public bool Automatic { get; set; }
        public string Colour { get; set; }

        public Vehicle()
        {
            Colour = "Green";
        }

        public Vehicle(int wheels, bool automatic, string colour)
        {
            this.Wheels = wheels;
            this.Automatic = automatic;
            this.Colour = colour;
        }
    }

    public class Tank : Vehicle
    {
        public int ShellSize { get; set; }
    }
}

Here we have a base class Vehicle and Tank inherits from that.  We then create a tank and specify its shell size.  We then output the shellsize and colour to the console.  The results are as follows which tells us that the default constructor has been inherited by Tank.

So we now lnow that default constructors are inherited when we subclass.

If we wrote our tank class as follows and ran our program then the tanks colour would be grey.

    public class Tank : Vehicle
    {
        public int ShellSize { get; set; }

        public Tank()
        {
            Colour = "Grey";
        }
    }

We can therefore see that although a default construtor is inherited when we sublass, it can be overrriden by simply providing a new default constructor in the sub class.  Now what actually happens here is that the default constructor in the base class runs and then the default constructor in the sub class runs and overwrites what was set in the base constructor - this isn't an override in the normal OO sense of things, it is just that our sub class constructor runs after the base one.  The point here is that default constructors are always run in the base class.  Consider the following code:

Module MainModule
    Sub Main()
        Dim a As New GrandChildClass()

        Console.ReadLine()
    End Sub
End Module

Public Class BaseClass
    Public Sub New()
        Console.WriteLine("Base" & Environment.NewLine)
    End Sub
End Class

Public Class ChildClass : Inherits BaseClass
    Public Sub New()
        Console.WriteLine("Child" & Environment.NewLine)
    End Sub
End Class

Public Class GrandChildClass : Inherits ChildClass
    Public Sub New()
        Console.WriteLine("GrandChild" & Environment.NewLine)
    End Sub
End Class

If we run this then we get the following results:

These results prove that the default constructor in a base clas is always executed and that they are executed in the order of the inheritance tree.

When we are working with overloaded constructors then these are not inherited.  We can prove this with the following code:

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

namespace OverloadedConstructors
{
    public class Program
    {
        static void Main(string[] args)
        {
            Tank myTank = new Tank(8, true, "Green");

            Console.WriteLine(myTank.Colour);

            Console.ReadKey();
        }
    }

    public class Vehicle
    {
        public int Wheels { get; set; }
        public bool Automatic { get; set; }
        public string Colour { get; set; }

        public Vehicle()
        {

        }

        public Vehicle(int wheels, bool automatic, string colour)
        {
            this.Wheels = wheels;
            this.Automatic = automatic;
            this.Colour = colour;
        }
    }

    public class Tank : Vehicle
    {
        public int ShellSize { get; set; }
    }
}

If we try and compile this code then it will not compile and will give the following error:

So from this we can see that overloaded constructors are not inherited in sub classes.  If you wish to expose an overloaded constructor then you need to write it again in the sub class.  However you do not need to write the implementation code again, just the method stub and you can then pass the call down to the base class as follows:

    public class Tank : Vehicle
    {
        public int ShellSize { get; set; }

        public Tank(int wheels, bool automatic, string colour) : base(wheels, automatic, colour)
        {

        }
    }

The code for doing this sort of thing in VB.net would look something like this:

Module Module1
    Sub Main()
        Dim robin As New Bird("Red")

        System.Console.ReadKey()
    End Sub
End Module

Class Animal
    Sub New()
        System.Console.WriteLine("Animal Constructor")
    End Sub

    Sub New(colour As String)
        System.Console.WriteLine("Overloaded Animal Constructor " & colour)
    End Sub
End Class

Class Bird : Inherits Animal
    Sub New()
        System.Console.WriteLine("Bird Constructor")
    End Sub

    Sub New(colour As String)
        MyBase.New(colour)
    End Sub
End Class

When we override normal virtual methods in C#, we may then also call the method we have overridden in the base class using the base keyword.  With constructors we can do something simillar with one subtle difference.  In normal method overriding we decide where abouts in the overriding code we place the call to execute the base method.  The overriding method always runs first but we can then either call the base method and then do our overridden code, or we can execute our overridden code and then call the base method.  The following code illustrates this flexibility:

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

namespace MoreConstructors
{
    class Program
    {
        static void Main(string[] args)
        {
            Vehicle car = new AutomaticVehicle();

            car.SomeMethod();

            Console.ReadKey();
        }
    }

    public class Vehicle
    {
        public int Wheels { get; set; }
        public string Colour { get; set; }

        public virtual void SomeMethod()
        {
            Console.WriteLine("Base class code goes here\n\n");
        }
    }

    public class AutomaticVehicle : Vehicle
    {
        public int ShellSize { get; set; }

        public override void SomeMethod()
        {
            Console.WriteLine("Sub class code goes here\n\n");

            base.SomeMethod();
        }
    }
}

In this example the base method runs after our sub classed method but you could easily swap this around by just swaping the two lines which call SomeMethod.  You would do this or not depending on the nature and logic of your classes or you may not call the base method at all.  Typically you may want to consider if you are ading to the base method - ie using it as a point in time to plugin some additional functionality or whether you want to completley override the base method.  With the former you would call base and with the latter you would not.

So with constructors we can do the same thing but we get no choice in the order of things.

Consider the following example:

using System;

namespace Constructors.UI
{
    public class Program
    {
        static void Main(string[] args)
        {
            AjaxPage ap = new AjaxPage(true);
            Console.ReadKey();
        }
    }

    public class Page
    {
        public Page()
        {

        }       

        public Page(bool saveTodatbase)
        {
            Console.WriteLine("Page saving state\n");
        }
    }

    public class AjaxPage : Page
    {
        public AjaxPage(bool saveTodatbase) : base(saveTodatbase)
        {
            Console.WriteLine("AjaxPage saving state\n");
        }
    }
}

The output from the above program looks like this.

So from the Console.WriteLine statements I put in there we can see that both constructors ran and that the base constructor ran first.

Inferred Rules

So from all of this research we can see that there are a number of rules which we can define as follows.

1.  If you do not create a default constructor then one is created for you under the hood

2.  If you instantiate a class which is a sublass, then the appropriate constructor will run in the sub class as you would expect but the default constructor is also executed in the base class.  The order of events is that the base class default constructor runs first followed by the appropriate constructor in the child class.  This works no matter how many levels of base classes you have.  All the default constructors are run in the order of the hierarchy, followed finally by the appropriate constructor in the concrete child class.

3. You do not need to normally create a default constructor as one is added for you.  If you create a class with an overloaded constructor and create instances of that class using that overloaded constructor then you still do not need to create a default constructor.  If however in the previous scenario with the overloaded constructor you then try and also create instance of that class using the default constructor then this will not work and in fact will not even compile - in this scenario then you do have to explicitly create a default constructor.

4. All default constructors will always run unless an overloaded constructor is used.  So if we have classes A, B, C and B sublcasses A and C subclasses B then we have the followng possibilities.

Create an instance of C using the default constructor - All default construtcors will run in the order A, B, C

Create an instance of C using an overloaded constructor in C - Construtcors will run in the order A - default, B - default, C - overloaded

Create an instance of C using an overloaded constructor in C and that overloaded constructor calls an overloaded constructor in B - Construtcors will run in the order A - default, B - overloaded, C - overloaded

So default ones in each class only run if an overloaded one isn't run (unless they are explicitly called of course)

5. Constructors are not inherited.  If you have class B which sub classes A and A has an overridden constructor for example then this will not be available when creating new instances of class B.  You will need to recreate the constructor in B.  You don't need to copy and paste all the code withing the constructor though - you just pass the call on to the base class using base in C# or MyBase in VB.net.

Constructor Scenarios (C#)

01. Create an instance of a class with no explicit constructors.

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

namespace CS_Scenario_01
{
    class Program
    {
        static void Main(string[] args)
        {
            GamePlayer dave = new GamePlayer();

            Console.WriteLine(dave);

            Console.ReadKey();
        }
    }

    class GamePlayer
    {
        public string PlayerName { get; set; }
        public int Health { get; set; }

        public override string ToString()
        {
            return String.Format("I am player \"{0}\" with {1}% health", PlayerName, Health);
        }
    }
}

02. Create an instance of a class with an explicit default constructor.

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

namespace CS_Scenario_02
{
    class Program
    {
        static void Main(string[] args)
        {
            GamePlayer dave = new GamePlayer();

            Console.WriteLine(dave);

            Console.ReadKey();
        }
    }

    class GamePlayer
    {
        public string PlayerName { get; set; }
        public int Health { get; set; }

        public GamePlayer()
        {
            Health = 100;
        }

        public override string ToString()
        {
            return String.Format("I am player \"{0}\" with {1}% health", PlayerName, Health);
        }
    }
}

03. Create an instance of a class with an explicit overloaded constructor and no default constructor.

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

namespace CS_Scenario_03
{
    class Program
    {
        static void Main(string[] args)
        {
            GamePlayer dave = new GamePlayer("Dave");

            Console.WriteLine(dave);

            Console.ReadKey();
        }
    }

    class GamePlayer
    {
        public string PlayerName { get; set; }
        public int Health { get; set; }

        public GamePlayer(string name)
        {
            PlayerName = name;
        }

        public override string ToString()
        {
            return String.Format("I am player \"{0}\" with {1}% health", PlayerName, Health);
        }
    }
}

04. Create an instance of a class with an explicit overloaded constructor and a default constructor.

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

namespace CS_Scenario_04
{
    class Program
    {
        static void Main(string[] args)
        {
            GamePlayer dave = new GamePlayer("Dave");

            Console.WriteLine(dave);

            Console.ReadKey();
        }
    }

    class GamePlayer
    {
        public string PlayerName { get; set; }
        public int Health { get; set; }

        public GamePlayer()
        {
            Health = 100;
        }

        public GamePlayer(string name)
        {
            PlayerName = name;
        }

        public override string ToString()
        {
            return String.Format("I am player \"{0}\" with {1}% health", PlayerName, Health);
        }
    }
}

 

05. Create an instance of a class with an explicit default constructor and call another constructor using this - ie the this keyword.

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

namespace CS_Scenario_05
{
    class Program
    {
        static void Main(string[] args)
        {
            GamePlayer dave = new GamePlayer();

            Console.WriteLine(dave);

            Console.ReadKey();
        }
    }

    class GamePlayer
    {
        public string PlayerName { get; set; }
        public int Health { get; set; }

        public GamePlayer() : this("Dave")
        {
            Health = 100;
        }

        public GamePlayer(string name)
        {
            PlayerName = name;
        }

        public override string ToString()
        {
            return String.Format("I am player \"{0}\" with {1}% health", PlayerName, Health);
        }
    }
}

 

06. Create an instance of a class with an explicit overloaded constructor and call another constructor using this - ie the this keyword.

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

namespace CS_Scenario_06
{
    class Program
    {
        static void Main(string[] args)
        {
            GamePlayer dave = new GamePlayer("Dave");

            Console.WriteLine(dave);

            Console.ReadKey();
        }
    }

    class GamePlayer
    {
        public string PlayerName { get; set; }
        public int Health { get; set; }

        public GamePlayer()
        {
            Health = 100;
        }

        public GamePlayer(string name) : this()
        {
            PlayerName = name;
        }

        public override string ToString()
        {
            return String.Format("I am player \"{0}\" with {1}% health", PlayerName, Health);
        }
    }
}

 

07. Create an instance of a class which subclasses another class. Neither classes have any explicit constructors.

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

namespace CS_Scenario_07
{
    class Program
    {
        static void Main(string[] args)
        {
            CounterStrikGamePlayer dave = new CounterStrikGamePlayer();

            Console.WriteLine(dave);

            Console.ReadKey();
        }
    }

    class GamePlayer
    {
        public string PlayerName { get; set; }
        public int Health { get; set; }

        public override string ToString()
        {
            return String.Format("I am player \"{0}\" with {1}% health", PlayerName, Health);
        }
    }

    class CounterStrikGamePlayer : GamePlayer
    {
        public bool HasDefuseKit { get; set; }
    }
}

 

08. Create an instance of a class which subclasses another class. Both classes have a default constructor but we don't call any base constructors explicitly.

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

namespace CS_Scenario_08
{
    class Program
    {
        static void Main(string[] args)
        {
            CounterStrikGamePlayer dave = new CounterStrikGamePlayer();

            dave.PlayerName = "Dave";

            Console.WriteLine(dave);

            Console.ReadKey();
        }
    }

    class GamePlayer
    {
        public string PlayerName { get; set; }
        public int Health { get; set; }

        public GamePlayer()
        {
            Health = 100;
        }

        public override string ToString()
        {
            return String.Format("I am player \"{0}\" with {1}% health", PlayerName, Health);
        }
    }

    class CounterStrikGamePlayer : GamePlayer
    {
        public bool HasDefuseKit { get; set; }
        public CounterStrikGamePlayer()
        {
            Health = Health + 10;
        }
    }
}

 

09. Create an instance of a class which subclasses another class. Both classes have a default constructor and we do call the base constructor explicitly.

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

namespace CS_Scenario_09
{
    class Program
    {
       static void Main(string[] args)
        {
            CounterStrikGamePlayer dave = new CounterStrikGamePlayer();

            dave.PlayerName = "Dave"

            Console.WriteLine(dave);

            Console.ReadKey();
        }
    }

    class GamePlayer
    {
        public string PlayerName { get; set; }
        public int Health { get; set; } 

        public GamePlayer()
        {
            Health = 100;
        }

        public override string ToString()
        {
            return String.Format("I am player \"{0}\" with {1}% health", PlayerName, Health);
        }
    }

    class CounterStrikGamePlayer : GamePlayer
    {
        public bool HasDefuseKit { get; set; } 

        public CounterStrikGamePlayer() : base()
        {
            Health = Health + 10;
        }
    }
}

10. Create an instance of a class which subclasses another class. The sub class has an overloaded constructor and only calls that.

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

namespace CS_Scenario_10
{
    class Program
    {
        static void Main(string[] args)
        {
            CounterStrikGamePlayer dave = new CounterStrikGamePlayer("Sarah"); 

            Console.WriteLine(dave);

            Console.ReadKey();
        }
    }

    class GamePlayer
    {
        public string PlayerName { get; set; }
        public int Health { get; set; } 

        public GamePlayer()
        {
            Health = 100;
        }

        public override string ToString()
        {
            return String.Format("I am player \"{0}\" with {1}% health", PlayerName, Health);
        }
    }

    class CounterStrikGamePlayer : GamePlayer
    {
        public bool HasDefuseKit { get; set; } 

        public CounterStrikGamePlayer(string name)
        {
            PlayerName = name;
        }
    }
}

 

11. Create an instance of a class which subclasses another class. The sub class has an overloaded constructor which then calls the base overloaded constructor as well.

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

namespace CS_Scenario_11
{
    class Program
    {
        static void Main(string[] args)
        {
            CounterStrikGamePlayer dave = new CounterStrikGamePlayer("Sarah"); 

            Console.WriteLine(dave);

            Console.ReadKey();
        }
    }

    class GamePlayer
    {
        public string PlayerName { get; set; }
        public int Health { get; set; } 

        public GamePlayer()
        {
            Health = 100;
        }

        public GamePlayer(string name)
        {
            PlayerName = name.ToUpper();
        }

        public override string ToString()
        {
            return String.Format("I am player \"{0}\" with {1}% health", PlayerName, Health);
        }
    }

    class CounterStrikGamePlayer : GamePlayer
    {
        public bool HasDefuseKit { get; set; } 

        public CounterStrikGamePlayer(string name) : base(name)
        {
            PlayerName = name;
        }
    }
}

Constructor Scenarios (VB.net)

01. Create an instance of a class with no explicit constructors.

Module Module1

    Sub Main()
        Dim dave As New GamePlayer() 

        Console.WriteLine(dave)

        Console.ReadKey()
    End Sub

End Module

Class GamePlayer
    Public Property PlayerName As String
    Public Property Health As Integer

    Public Overrides Function ToString() As String
        Return String.Format("I am player ""{0}"" with {1}% health", PlayerName, Health)
    End Function
End Class

02. Create an instance of a class with an explicit default constructor.

Module Module1 
    Sub Main()
        Dim dave As New GamePlayer()

        Console.WriteLine(dave)

        Console.ReadKey()
    End Sub 
End Module

Class GamePlayer
    Public Property PlayerName As String
    Public Property Health As Integer

    Public Sub New()
        Health = 100
    End Sub

    Public Overrides Function ToString() As String
        Return String.Format("I am player ""{0}"" with {1}% health", PlayerName, Health)
    End Function
End Class

03. Create an instance of a class with an explicit overloaded constructor and no default constructor.

 Module Module1 
    Sub Main()
        Dim dave As New GamePlayer("Dave"

        Console.WriteLine(dave)

        Console.ReadKey()
    End Sub
End Module

Class GamePlayer
    Public Property PlayerName As String
    Public Property Health As Integer

    Public Sub New(name As String)
        PlayerName = name
    End Sub

    Public Overrides Function ToString() As String
        Return String.Format("I am player ""{0}"" with {1}% health", PlayerName, Health)
    End Function
End Class

04. Create an instance of a class with an explicit overloaded constructor and a default constructor.

Module Module1

    Sub Main()
        Dim dave As New GamePlayer("Dave"

        Console.WriteLine(dave)

        Console.ReadKey()
    End Sub

End Module

Class GamePlayer
    Public Property PlayerName As String
    Public Property Health As Integer

    Public Sub New()
        Health = 100
    End Sub

    Public Sub New(name As String)
        PlayerName = name
    End Sub

    Public Overrides Function ToString() As String
        Return String.Format("I am player ""{0}"" with {1}% health", PlayerName, Health)
    End Function
End Class

05. Create an instance of a class with an explicit default constructor and call another constructor using this - ie the this keyword.

Module Module1

    Sub Main()
        Dim dave As New GamePlayer() 

        Console.WriteLine(dave)

        Console.ReadKey()
    End Sub

End Module

Class GamePlayer
    Public Property PlayerName As String
    Public Property Health As Integer

    Public Sub New()
        Me.New("Dave"

        Health = 100
    End Sub

    Public Sub New(name As String)
        PlayerName = name
    End Sub

    Public Overrides Function ToString() As String
        Return String.Format("I am player ""{0}"" with {1}% health", PlayerName, Health)
    End Function
End Class

06. Create an instance of a class with an explicit overloaded constructor and call another constructor using this - ie the this keyword.

Module Module1
    Sub Main()
        Dim dave As New GamePlayer("Dave")

        Console.WriteLine(dave)

        Console.ReadKey()
    End Sub
End Module

Class GamePlayer
    Public Property PlayerName As String
    Public Property Health As Integer

    Public Sub New()
        Health = 100
    End Sub

    Public Sub New(name As String)
        Me.New()
        PlayerName = name
    End Sub

    Public Overrides Function ToString() As String
        Return String.Format("I am player ""{0}"" with {1}% health", PlayerName, Health)
    End Function
End Class

07. Create an instance of a class which subclasses another class. Neither classes have any explicit constructors.

Module Module1
    Sub Main()

        Dim dave As New CounterStrikeGamePlayer()

        Console.WriteLine(dave)

        Console.ReadKey()
    End Sub
End Module

Class GamePlayer
    Public Property PlayerName As String
    Public Property Health As Integer

    Public Overrides Function ToString() As String
        Return String.Format("I am player ""{0}"" with {1}% health", PlayerName, Health)
    End Function
End Class

Class CounterStrikeGamePlayer : Inherits GamePlayer
    Public Property HasDefuseKit As Boolean
End Class

08. Create an instance of a class which subclasses another class. Both classes have a default constructor but we don't call any base constructors explicitly.

Module Module1
    Sub Main()
        Dim dave As New CounterStrikeGamePlayer()

        dave.PlayerName = "Dave"

        Console.WriteLine(dave)

        Console.ReadKey()
    End Sub
End Module

Class GamePlayer
    Public Property PlayerName As String
    Public Property Health As Integer

    Public Sub New()
        Health = 100
    End Sub

    Public Overrides Function ToString() As String
        Return String.Format("I am player ""{0}"" with {1}% health", PlayerName, Health)
    End Function
End Class

Class CounterStrikeGamePlayer : Inherits GamePlayer
    Public Property HasDefuseKit As Boolean

    Public Sub New()
        Health = Health + 10
    End Sub
End Class

09. Create an instance of a class which subclasses another class. Both classes have a default constructor and we do call the base constructor explicitly.

Module Module1
    Sub Main()
        Dim dave As New CounterStrikeGamePlayer()

        dave.PlayerName = "Dave"

        Console.WriteLine(dave)

        Console.ReadKey()
    End Sub

End Module

Class GamePlayer
    Public Property PlayerName As String
    Public Property Health As Integer

    Public Sub New()
        Health = 100
    End Sub

    Public Overrides Function ToString() As String
        Return String.Format("I am player ""{0}"" with {1}% health", PlayerName, Health)
    End Function
End Class

Class CounterStrikeGamePlayer : Inherits GamePlayer

    Public Property HasDefuseKit As Boolean

    Public Sub New()
        MyBase.New()

        Health = Health + 10
    End Sub
End Class

10. Create an instance of a class which subclasses another class. The sub class has an overloaded constructor and only calls that.

Module Module1
    Sub Main()
        Dim dave As New CounterStrikeGamePlayer("Sarah")

        Console.WriteLine(dave)

        Console.ReadKey()
    End Sub
End Module

Class GamePlayer
    Public Property PlayerName As String
    Public Property Health As Integer

    Public Sub New()
        Health = 100
    End Sub

    Public Overrides Function ToString() As String
        Return String.Format("I am player ""{0}"" with {1}% health", PlayerName, Health)
    End Function
End Class

Class CounterStrikeGamePlayer : Inherits GamePlayer

    Public Property HasDefuseKit As Boolean

    Public Sub New(name As String)
        PlayerName = name
    End Sub
End Class

11. Create an instance of a class which subclasses another class. The sub class has an overloaded constructor which then calls the base overloaded constructor as well.

Module Module1
    Sub Main()
        Dim sarah As New CounterStrikeGamePlayer("Sarah")

        Console.WriteLine(sarah)

        Console.ReadKey()
    End Sub
End Module

Class GamePlayer
    Public Property PlayerName As String
    Public Property Health As Integer

    Public Sub New()
        Health = 100
    End Sub
 

    Public Sub New(name As String)
        PlayerName = name.ToUpper()
    End Sub

    Public Overrides Function ToString() As String
        Return String.Format("I am player ""{0}"" with {1}% health", PlayerName, Health)
    End Function
End Class

Class CounterStrikeGamePlayer : Inherits GamePlayer
    Public Property HasDefuseKit As Boolean

    Public Sub New(name As String)
        MyBase.New(name)
        PlayerName = name
    End Sub
End Class