advertisement
Constructors and Destructors in C#
A C# Class can contain one or more special member functions having the same name as the class Constructors. Constructors are executed when an object of the class is created to initialize the object with data. A C# class can also have a destructor (only one is allowed per class), which is a special method and also has the same name as the class but is prefixed with a special symbol ~. A destructor of an object is executed when the object is no longer required to de-allocate the memory of the object
Constructors
A class can contain multiple variables whose declaration and initialization become difficult to track if they are done within different blocks. Likewise, there may be other startup operations that to be performed in an application like opening a file and so forth. To simplify these tasks, a constructor is used. A constructor is a method having the same name as that of the class. Constructors can initialize the variables of a class or perform startup operations only once when the object of the class is instantiated. They are automatically executed whenever an instance of a class is created.
Access Modifiers are as follows:
- Public: Specifies that the constructor will be called whenever a class is instantiated. This instantiation can be done from anywhere and from any assembly.
- Private: Specifies that this constructor cannot be invoked by an instance of a class.
- Protected: Specifies that the base class will initialize on its own whenever its derived classes are created. Here, the class object can only be created in the derived classes.
- Internal: Specifies that the constructor has access limited to the current assembly. It cannot be accessed outside the assembly.
//Example 1: Constructor
public class circle
{
public circle()
{
Console.WriteLine("Hello");
Console.ReadKey();
}
}
class Program
{
static void Main(string[] args)
{
circle circleobj = new circle();
}
}
This program will generate a compile-time error because an instance of the Circle class attempts to invoke the constructor which is declared as private. This is an illegal attempt. Private constructors are used to prevent class instantiation. If a class has defined only private constructors, the new keyword cannot be used to instantiate the object of the class. This means no other class can use the data members of the class that has only private constructors. Therefore, private constructors are only Used if a class contains only static data members. This is because static members are invoked using the class name.
//Example 2: Constructor
class employee
{
public string empname;
public int empage;
public string deptname;
public employee(String name, int age)
{
empname = name;
empage = age;
deptname = "Web Developement";
}
}
class program
{
static void Main(string[] args)
{
employee empobj = new employee("John", 25);
Console.WriteLine(empobj.deptname);
Console.WriteLine(empobj.empname);
Console.WriteLine(empobj.empage);
Console.ReadKey();
}
}
In this program, a constructor is created for the class employees. When the class is instantiated. th constructor is invoked with the parameters John and 25. These values are stored in the class variables empName and empAge respectively. The department of the employee is then displayed in the console window.
Note: Constructors have no return type. This is because the implicit return type of a constructor is the class itself. It is possible to have overloaded constructors in C#.
Default Constructors
C# creates a default constructor for a class if no constructor is specified within the class. The default constructor automatically initializes all the numeric data type instance variables of the class to zero. you define a constructor in the class, the default constructor is no longer used.
Static Constructors
A static constructor is used to initialize static variables of the class and to perform a particular action only once. It is invoked before any static member of the class is accessed, You can have only one static constructor in the class. The static keyword is used to declare a constructor as static. A static constructor does not take any parameters and does not use any access modifiers because it is invoked directly by the CLR instead of the object. In addition, it cannot access any non-static data member of the class.
How static constructors are created and invoked.
//Example 4: Static Constructor
class multi
{
static int valone = 10;
static int product;
static multi()
{
Console.WriteLine("Static constructor initialized");
product = valone * valone;
}
public static void Method()
{
Console.WriteLine("Value of product: " + product);
}
static void Main(string[] args)
{
multi.Method();
Console.ReadKey();
}
}
In this program, the static constructor Multi () is used to initialize the static variable product. Here, the static constructor is invoked before the static method Method () is called from the Main () method.
OUTPUT:-
Static Constructor initialized
Value of product = 100
Constructor Overloading
The concept of declaring more than one constructor in a class is called constructor overloading. The process of overloading constructors is similar to overloading methods. Every constructor has a signature similar to that of a method. You can declare multiple constructors in a class wherein each constructor will have different signatures. Constructor overloading is used when different objects of the class might want to use different initialized values. Overloaded constructors reduce the task of assigning different values to member variables each time when required by different objects of the class.
//Example 5: Constructor Overloading
public class rectangle
{
double length;
double breadth;
public rectangle()
{
length = 13.5;
breadth = 20.5;
}
public rectangle(double len, double width)
{
length = len;
breadth = width;
}
public double area()
{
return length * breadth;
}
static void Main(string[] args)
{
rectangle recobj = new rectangle();
Console.WriteLine("Area of rectangle is:" + recobj.area());
rectangle recobj2 = new rectangle(2.5, 6.9);
Console.WriteLine("Area of rectangle is :" + recobj2.area());
Console.ReadKey();
}
}
In this code, two constructors are created having the same name, Rectangle. However, the signatures of these constructors are different. Hence, while calling the method Area () from the main() method, the parameters passed to the calling method are identified. Then, the corresponding is used to initialize the variable's length and breadth. Finally, the multiplication operation is performed on these variables and the area values are displayed as the output.
OUTPUT:-
Area of rectangle1 = 276. 75
Area of rectangle2 = 17.25
Destructors
A destructor is a special method that has the same name as the class but starts with the character ~ before the class name. Destructors immediately de-allocate the memory of objects that are no longer required. They are invoked automatically when the objects are not in use. You can define only one destructor in a class. Apart from this, destructors have some more features. These features are as follows:
- Destructors cannot be overloaded or inherited.
- Destructors cannot be explicitly invoked.
- Destructors cannot specify access modifiers and cannot take parameters.
//Example 5: Destructor
class employee
{
private int empid;
private string empname;
private int empage;
private double salary;
employee(int id, string name, int age, double salary)
{
empid = id;
empname = name;
empage = age;
this.salary = salary;
}
~employee()
{
Console.WriteLine("Destructor of employee called");
}
static void Main(string[] args)
{
employee empobj = new employee(1, "john", 25, 1000.00);
Console.WriteLine("Emp ID:" + empobj.empid);
Console.WriteLine("Emp Name:" + empobj.empname);
Console.WriteLine("Emp Age:" + empobj.empage);
Console.WriteLine("Emp Salary:" + empobj.salary);
Console.ReadKey();
}
}
In this code, the destructor ~Employee is created having the same name as that of the class and the constructor. The destructor is automatically called when the object empobj is no longer required to be used. However, when this will happen cannot be determined and hence, you have no control over when the destructor is going to be executed.
advertisement
Conversation
Your input fuels progress! Share your tips or experiences on prioritizing mental wellness at work. Let's inspire change together!
Join the discussion and share your insights now!
Comments 0