Constructor is method of class to allocate the memory of object and initialize the variables of class.
When you declare a variable of a class, a special method must be called to initialize the members of that class. This method is automatically provided for every class and it is called a constructor.
We’ll be covering the following topics in this tutorial:
Default Constructor
Whenever you create, a new class, a constructor is automatically provided to it. This particular constructor is called the default constructor. You have the option of creating it or not. Although a constructor is created for your class, you can customize its behavior or change it tremendously.
A constructor holds the same name as its class and doesn’t return any value, not even void. Here is an example:
public class Exercise
{
public void welcome ()
{
console.writeline (“This is an Exercise”);
}
Public exercise ()
{
}
}
Like every method, a constructor can be equipped with a body. In this body, you can access any of the member variables (or methods(s) of the same class. When introducing classes other than the main class, we saw that, to use such a class, you can declare its variable and allocate memory using the new operator. You can notice that we always included the parentheses when declaring such a variable. Here is an example:
public class class!
{
static void Main()
{
Exercise exo = new Exercise();
}
}
In this case, the parentheses indicate that we are calling the default constructor to instantiate the class.
Consider the following Example:
The demonstration of constructor.
using System;
public class Exercise
{
public void welcome()
{
console.writeLine(“The wonderful world of c# programming”);
}
console.writeLine(“The Exercise class is now available”);
public Exercise()
{
}
}
public class class! r
t
static void Main()
{
Exercise exo = new Exercise();
}
}
OUTPUT:
The Exercise class is now available
This shows that, when a class has been instantiated, its constructor is the first method to be called. For this reason, you can use a constructor to initialize a class, that is, to assign default values to its member variables. When a constructor is used to initialize a variable declared for a class. That constructor is referred to as an instance constructor.
Parameterized Constructor
We saw that there is always a default constructor for a new class that you create; you just the option of explicitly creating one or not. The default constructor as we saw it doesn’t take arguments: this is not a rule, it is simply assumed. Instead of a default constructor, you may want to create a constructor that takes argument. Here is an example:
public class Quadrilateral
{
public Quadrilateral(double side)
{
}
}
With this type of constructor, when you declare an instance of the class, you can use this new constructor to initialize the class. Here is an example:
using System;
public class Quadrilateral
{
public Quadrilateral(double side)
{
}
}
public class classl
{
static void Main()
{
Quadrilateral Square = new Quadrilateral(6.55);
}
}
If you create one constructor for your class and pass at least one argument to that constructor, the automatic default constructor created by the compiler disappears. This implies that if you declare an instance of the class and use the default constructor to initialize it, you would receive an error when you compile the program. Based on this rule, the following program will not compile:
using System;
public class Quadrilateral
{
public Quadrilateral(double side) {
}
}
public class Classl
{
static void Main()
{
Quadrilateral Square = new Quadrilateral();
}
}
If you still want to use the default constructor in a class after creating a constructor that takes at least one argument, you must explicitly create that default constructor.
Private Constructor
A private constructor is a special instance (default) constructor. It is commonly used in class that contain static members only, if a class has one or more private constructors and no blic constructors, then other classes (except nested ‘classes) are not allowed to create instances of this class. For example-
Class NLog
{
II private constructor
private NLog() { }
public static double e = 2.71828;
}
The declaration of the empty constructor prevents the automatic generation of a default constructor. Note that if you don’t use an access modifier with the constructor it will still be private by default. However, the private modifier is usually used explicitly to make it clear that the class cannot be instantiated.
Private constructors are useful to prevent creation of a class when these are no instance fields or methods, such as the Math class, or when a method is called to obtain an instance of a class.
The following is an example of a class using a private constructor.
using System;
public class Myclass
{
private Myclass() {}
public static int counter;
public static int InerementCounter()
{
return ++counter;
}
}
class MainClass
{
static void Main ()
{
II if you uncomment the following statement, it will generate
II an error because the constructor is inaccessible
II Myclass myobject = new Myclass(); //error
Myclass.counter = 100;
Myclass.lncrementcounter();
Console.wr;teL;ne (“New count: {O}”, Myclass.counter);
}
}
OUTPUT:
New count : 100
Notice that is you uncoment the following statement from the example, it will generate
an error because the constructor is in assessable due to its protection level : /I Myclass Myobject
= new MyClass 0;// error.
Static Constructor
Like the above described instance constructors, a static constructor is used to initialize a class. The main difference is that a static constructor works internally, in the class. Therefore, it is not used to initialize a variable of the class and you can never declare a variable of a class using a static constructor.
To make a constructor static, when creating it, type the static keyword to its left. Here is an example:
using system;
public class Quadrilateral
{
static Quadrilateral()
{
}
}
public class class1
{
static void Main()
{
/* use the default constructor to initialize an
instance of the class */
Quadrilateral Square = new Quadrilateral
}
}
In the above class, a static constructor is created for the class but the default constructor is still available and it is used to instantiate the class. Notice· that. static constructors are not inherited, and cannot be called .directly.
After the class loader loads a class that will soon be used, but before it continues normal execution, it executes the static constructor for that class. Because of this process, you are guaranteed that classes are always initialized before they are used. The exact timing of atic constructor execution is implementation-dependent, but is subject to the following rules:
• The static constructor for a class is executed before any instance of the class is created.
• The static constructor for a class is executed before any static members of the class are referenced.
• The static constructor for a class executes at most one time during a single program instantiation.
Static Field Initializations
The most common use for a static constructor is to initialize the static fields of a .class. This is because when you initialize a static field directly at its point of declaration, the compiler conceptually converts the initialization into an assignment inside the static constructor. In other words:
class Example
{
private static wibble w = new wibble( };
}
is effectively converted by the compiler into
class Example
{
static Example( )
{
w = new wibble( );
}
private static wibble w;
}
Static Constructor Restrictions
Understanding the following four restrictions on the syntax of static constructors will help you understand how the common language runtime uses static constructors:
• You cannot call a static constructor.
• You cannot declare a static constructor with an access modifier.
• You cannot declare a static constructor with parameters.
• You cannot use this keyword in a static constructor.
Constructor Overloading
A constructor is the primary method of a class. It allows the programmer to initialize a variable of a class when the class is instantiated. A constructor that plays this role of initializing an instance of a class is also called an instance constructor. Most of the time, you don’t even need to create a constructor, since one is automatically provided to any class you create. Sometimes too, as we have seen in some classes, you need to create your own class as you judge it necessary. And sometimes, a single constructor may not be sufficient. For example, when creating a class, you may decide, or find out, that there must be more than one way for a user to initialize a variable.
Like any other method, a constructor can be overloaded. In other words, you can create a class and give it more than one constructor. The same rules used on overloading regular methods also apply to constructors: the different constructors must have different number of arguments or a different type of arguments.
Constructor overloading
using·system;
public class Applicant
{
public string FullName;
public string Address;
public string City;
public string State;
public string zIPcode;
public string sex;
public string DateofBirth;
public int weight;
public string Height;
public int Race;
II The default constructor, used to initialize an
II Applicant instance without much information
public Applicant()
{
this.FullName = “unknown”;
this.sex = “ungenerated”;
}
II A constructor that ;s passed only one argument public Applicant(string n)
{
this.FullName = n;
}
II A constructor with more than one argument
II This type is suitable to completely initialize a variable public Applicant(string n, string s, string dob)
{
this.FullName = n;
this. Sex = s;
this.dateofBirth = dob;
}
}
Public class exercise
{
Static applicant registerpersonalinformation()
{
string name;
char sex;
string gender = null;
string dob;
console.writeLine(” ** Motor vehicle Administration **”);
console.writeLine(“Applicant”s Registration”);
console.write(“Full Name: “);
name = console.ReadLine();
do
{
console.write(“sex(F=Female/M=Male): “);
sex = char.parse(console.ReadLine());
if( (sex != If’) && (sex != ‘F’) && (sex != ‘m’)
&& (sex != ‘M’) )
console.writeLine(“please enter a valid character”);
}while( (sex != If’) && (sex != ‘F’) &&
(sex != ‘m’) && (sex != ‘M’) );
if( (sex == If’) I I sex == ‘F’ )
gender = “Female”;
else if( (sex == ‘m’) I I (sex == ‘M’) )
gender = “Male”;
console.write(“date of Birth(mm/dd/yyyy): “);
dob = console.ReadLine();
Applicant person = new Applicant(name, gender, dob);
return person;
}
static void ShOW(Applicant person)
{
console.writeLine (“\n ** Motor vehicle Administration **”);
console.writeLine (” – Applicant’s personal Information -“);
console.writeLine(“Full Name: {0}”, person.FullName);
console.writeLine(“Sex: {0}”, person.sex);
console.writeLine(“Date of Birth: {0}\n”, person.DateOfBirth);
}
public static int Main()
{
Applicant App = new Applicant();
App = RegisterPersonalInformation();
ShOW(App);
return 0;
}
}
OUTPUT:
** Motor Vehicle Administration **
Applicant’s Registration
Full Name: S.K. Kataria
Sex(F=Female/M=Male): d
Please enter a valid character
Sex(F=Female/M=Male): M
Date of Birth(mm/dd/yyyy): 06/10/1972
** Motor Vehicle Administration **
– Applicant’s Personal Information —
Full Name: Dominique Monay
Sex: Male
Date of Birth: 06/10/1972
Destructor
Destructor is just opposite to the constructor, it destruct the memory of object allocated by constructor.
While a constructor is a method used to initialize an instance of a class, a destructor is used to destruct an instance of class when that variable is not used anymore. Like the constructor, the destructor has the same name as the class. To indicate that the method is a destructor, its name is preceded with a tilde symbol.
• A class can only have one destructor.
• Destructors cannot be inherited or overloaded.
• Destructors cannot be called. They are invoked automatically.
Here is an example of a destructor in a class:
Sample of destructor
using System;
class sampleclass
{
II Constructor
public sampleclass()
{
console.writeLine(“sampleclass – Constructor”);
}
~sampleClass()
{
console.writeLine(“Destructor of sampleclass”);
}
}
public class Newproject
{
static void Main()
{
sampleclass sample = new sampleClass();
console.writeLine(“welcome”);
}
}
OUTPUT:
SampleClass-Constructor
Welcome
Destructor of SampleClass
Like a (default) constructor, a destructor is automatically created for your class but you can also create it if you want. A class can have only one destructor. If you don’t create it, the compiler would create it for your class. If you create it, the compiler would not create another. A destructor cannot have an access level. A destructor is called when the memory that a class was used is no longer needed. This is done automatically by the compiler. For this reason, you will hardly need to create a destructor, since its job is automatically taken care of behind .the scenes by the compiler.