• Home
  •  Constructor, Parameter less and Parameterized Constructor

 Constructor, Parameter less and Parameterized Constructor

Agenda

Constructor in C#

C# Constructor Example

Example:

class Test {

Test() {

// constructor body

}

} //Here, Test() is a constructor; it has same name as that of the class and doesn’t
have a return type.

class Test1 {

void Test1() {

// method body

}

} //Here, Test1() has same name as that of the class. However, it has a return type
void. Hence, it’s a method not a constructor.

Test obj = new Test();

// At this time the code in the constructor will be executed

C# Constructor Overloading

User can create two or more constructor in a class. It is known as constructor overloading. Based on the number of the argument passed during the constructor call, the corresponding constructor is called.

Constructor Overloading:

public class Bank

{

public Bank() {

Console.WriteLine(“Bank Constructor”); // parameterless constructor

}

public Bank(String bankName, double interestRate, double depositRate)

{

Console.WriteLine(bankName + ” ” + interestRate +” “+depositRate); // parameterized constructor

}

}

static void Main()

{

Bank b1 = new Bank();

Bank b2 = new Bank();

Bank b3 = new Bank(“ICICI”, 8.5, 6.5);

Bank b4 = new Bank(“SBI”, 8.25, 6.25);

}

 public class Bank
{
public Bank() {
Console.WriteLine("Bank Constructor"); // parameterless constructor
}
private Bank(String bankName)
{
Console.WriteLine("Bank Constructor" + bankName); // private constructor
}

static Bank()
{
Console.WriteLine("Bank Static Constructor"); // static constructor User cannot call a static constructor directly. However, when they call a regular constructor, the static constructor gets called automatically.

}
public Bank(String bankName, double interestRate, double depositRate)
{
Console.WriteLine(bankName + " " + interestRate +" "+depositRate); // parameterized constructor
}
}

class Program
{
int i;
double d;
string s;

static void Main()
{
Bank b1 = new Bank();
Bank b2 = new Bank();
Bank b3 = new Bank("ICICI", 8.5, 6.5);
Bank b4 = new Bank("SBI", 8.25, 6.25);
// Bank b5 = new Bank("HDFC"); //Error CS0122 'Bank.Bank(string)' is inaccessible due to its protection level

Program obj = new Program(); //User have not created any constructor in the Program class. However, while creating an object, they are calling the constructor. C# automatically creates a default constructor. The default constructor initializes any uninitialized variable with the default value.
Console.WriteLine(obj.i);
Console.WriteLine(obj.i);
Console.WriteLine(obj.s);