Before reading this article, please go through the following articles:
- Object Oriented Programming Using C#: Part 1
- Object Oriented Programming Using C#: Part 2
- Object Oriented Programming Using C#: Part 3
- Object Oriented Programming Using C#: Part 5
- Object Oriented Programming Using C#: Part 6
- Object Oriented Programming Using C#: Part 7
- Object Oriented Programming Using C#: Part 8
- Object Oriented Programming Using C#: Part 9
- Object Oriented Programming Using C#: Part 10
C# Constructor
Part 1 was only about the basics of class constructors. In this lesson, we will discuss various types of constructors in detail.
Types of Properties
- Default Constructor
- Constructor Overloading
- Private Constructors
- Constructor Chaining
- Static Constructors
- Destructors
Please note a few basic concepts of constructors and ensure that your understanding is crystal clear, otherwise you can't understand OOP (constructors).
- Constructors have the same name as the class name.
- The purpose of constructors is for the initialization of member variables.
- A constructor is automatically invoked when the object is created.
- A constructor doesn't have any return type, not even void.
- If we want some code to be executed automatically then the code that we want to execute must be put in the constructor.
- We can't call the constructor explicitly.
The general form of a C# constructor is as follows.
modifier constructor_name(parameters)
{
// constructor body
}
The modifiers can be private, public, protected, or internal. The name of a constructor must be the name of the class for which it is defined. A constructor can take zero or more arguments. A constructor with zero arguments (that is no-argument) is known as the default constructor. Remember that there is not a return type for a constructor.
Default Constructors
A constructor without arguments is known as the default constructor. Remember that there is no return type for a constructor. That default constructor simply invokes the parameterless constructor of the direct base class.
Example
using System;
namespace DefaultConstructors
{
class Program
{
static void Main(string[] args)
{
car sportscar = new car();
Console.WriteLine("Car Model is :{0} ", sportscar.model_Id);
Console.WriteLine("Car Name is :{0}", sportscar.Maker_Name);
Console.ReadKey();
}
class car
{
private int model=-1;
private string maker = string.Empty;
public car()
{
//Default Constructor
}
public int model_Id
{
get {
return model ;
}
}
public string Maker_Name
{
get
{
return maker;
}
}
}
}
}
Output
In this simple example, we have the constructor without arguments or zero parameters which is the default constructor of the class. The output of the preceding example is empty member variables.
Please note one more point; if we remove the following code from Example 1 then the output is the same.
public car()
{
//Default Constructor
}
This means that if we do not define the constructor of the class the system will call the default constructor.
Constructors Overloading
First, we will discuss the purpose of constructor overloading; it's very important to have the clear understating of the preceding topic. There are many complex conditions that exist when designing OOP models and we need to initialize a different set of member variables for different purposes of a class. So we need to use constructor overloading. The definition of constructor overloading is.
Just like member functions, constructors can also be overloaded in a class. The overloaded constructor must differ in the number of arguments and/or type of arguments and/or order of arguments.
Example
using System;
namespace ConstructorsOverloading
{
class Program
{
static void Main(string[] args)
{
car sportscar1 = new car();
car sportscar2 = new car(2013, "mercedes");
car sportscar3 = new car("mercedes", 7.8);
Console.WriteLine("Constructor without arguments");
Console.WriteLine("Car Model is :{0} ", sportscar1.model_Id);
Console.WriteLine("Car Name is :{0}", sportscar1.Maker_Name);
Console.WriteLine("Car Engine Power is :{0}", sportscar1.Engine);
Console.WriteLine("\nConstructor with two arguments");
Console.WriteLine("Car Model is :{0} ", sportscar2.model_Id);
Console.WriteLine("Car Name is :{0}", sportscar2.Maker_Name);
Console.WriteLine("Car Engine Power is :{0}", sportscar2.Engine);
Console.WriteLine("\nConstructor with two arguments");
Console.WriteLine("Car Model is :{0} ", sportscar3.model_Id );
Console.WriteLine("Car Name is :{0} ", sportscar3.Maker_Name);
Console.WriteLine("Car Engine Power is :{0}", sportscar3.Engine );
Console.ReadKey();
}
class car
{
private int model = -1;
private string maker = string.Empty;
private double Enginetype= 0.0;
public car()
{
//Default Constructor
}
public car( int _model,string _maker)
{
model = _model;
maker = _maker;
}
public car(string _maker, double _power)
{
maker = _maker;
Enginetype = _power;
}
public int model_Id
{
get
{
return model;
}
set
{
model = value;
}
}
public string Maker_Name
{
get
{
return maker;
}
set
{
maker = value;
}
}
public double Engine
{
get
{
return Enginetype;
}
set
{
Enginetype = value;
}
}
}
}
}
Output
Dear reader, please note that in this example we have overloaded the constructor using three different objects, these are sportscar1, sportscar2, and sportscar3.
We notice that
- sportscar1 has no arguments (the default constructor is out of topic scope). So that member variable has default values that were assigned at the time of initialization.
- sportscar2 has two arguments that initialize the member variables model and name with the values 2013 and Mercedes respectively but do not initialize the Enginetype variable so it has the default value zero.
- sportscar3 has two arguments that initialize the member variables name and Enginetype with the values Mercedes and 7.8 respectively but do not initialize the model variable so it has the default value -1.
Private Constructors
Dear reader, as we know, the private access modifier is a bit of a special case. We neither create the object of the class nor can we inherit the class with only private constructors. But yes, we can have the set of public constructors along with the private constructors in the class and the public constructors can access the private constructors from within the class through constructor chaining. Private constructors are commonly used in classes that contain only static members.
using System;
namespace PrivateConstructors
{
class Program
{
static void Main(string[] args)
{
car sportscar = new car(2013);
Console.Read();
}
class car
{
public string carname;
private car()
{
carname = "lamborghini";
}
public car(int model):this()
{
Console.WriteLine("Model Year:{0}",model);
Console.WriteLine("Maker Name:{0}",carname);
}
}
}
}
This is a very simple example of private constructors in which we use a public constructor to call the private constructor.
Constructors Chaining
Dear reader, when a constructor invokes another constructor in the same class or in the base class of this class it is known as constructor chaining. It is a very useful technique for avoiding code duplication.
using System;
namespace Constructorchaining
{
class Program
{
static void Main(string[] args)
{
car sportscar = new car(7.8);
Console.Read();
}
class car
{
public string carname;
public int model;
public double engine;
public car(string _carname)
{
carname = _carname;
}
public car(int _model): this("lamborghini")
{
model= _model;
}
public car(double _engine) : this(2013)
{
engine = _engine;
Console.WriteLine("Model Year:{0}", model);
Console.WriteLine("Maker Name:{0}", carname);
Console.WriteLine("Engine Type:{0}", engine);
}
}
}
}
In the preceding example, we created three different classes with the name car having different parameter types, each one chaining the previous one to invoke the other constructor.
Static Constructors
The static constructor is the special type that does not take access modifiers or have parameters. It is called automatically to initialize the class before the first instance is created or any static members are referenced. The static constructor is not called directly. Users can't control the execution of the static constructor.
using System;
namespace staticconstructors
{
class Program
{
public class car
{
static car()
{
System.Console.WriteLine(@"Lamborghini is the best sports car owned by Audi AG 1998 (its static info)");
}
public static void Drive()
{
System.Console.WriteLine("Audi is the stable company");
}
}
static void Main()
{
car.Drive();
car.Drive();
Console.ReadKey();
}
}
}
Output
Note that the static constructor is called when the class is loaded the first time. When we again call "car.Drive" it will not call the static constructor.
Destructors
Dear reader, when we are working with OOP and creating objects in system memory it's necessary to clean the unwanted objects from the system memory The .NET framework has built in Garbage Collection to de-allocate memory occupied by the unused objects. A Destructor is a function with the same name as the name of the class but starting with the character ~. The Destructor can't have any of the modifiers private, public etcetera.
Example
class car
{
public car()
{
// constructor
}
~car()
{
// Destructor
}
}