Constructor Chaining In C Sharp
This program elaborate the concept of constructor chaining, with this concept we can remove the duplicacy of code in our program code.
------------------------------------------------------------------------------------------------------------
using System;
class Employee
{
private int e_id;
private string e_name;
private string e_address;
public Employee(){}
public Employee(int id)
{
e_id = id;
Console.WriteLine("Employee Id is " + e_id);
}
public Employee(int id, string name) : this(id)
{
e_name = name;
Console.WriteLine("Employee Name is " + e_name);
}
public Employee(int id, string name, string address) : this(id,name)
{
e_address = address;
Console.WriteLine("Employee Adddress is " + e_address);
}
}
class ConstructorChainingWithThisKeyword
{
static void Main()
{
Employee employee = new Employee(1,"Amit","#1111");
}
}
--------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
NOTE:- If we do not use constructor chaining then instead of the code write below
public Employee(int id)
{
e_id = id;
Console.WriteLine("Employee Id is " + e_id);
}
public Employee(int id, string name) : this(id)
{
e_name = name;
Console.WriteLine("Employee Name is " + e_name);
}
we need that code to replace the code given below
public Employee(int id)
{
e_id = id;
Console.WriteLine("Employee Id is " + e_id);
}
public Employee(int id, string name)
{
e_id = id; //here it create duplicacy.
e_name = name;
Console.WriteLine("Employee Id is " + e_id); //here it create duplicacy.
Console.WriteLine("Employee Name is " + e_name);
}
Constructor Chaining In C Sharp
Reviewed by Baljeet Singh
on
11:47
Rating:
No comments: