C# : Constructor


This article posted by Pradeep Reddy

Constructor

  • Constructor is a default method which is used to initialized the object.
  • Constructor will get invoked immediately after creating Object.
  • Constructor is used to initialized the default values for the instances variable.

Constructor are divided into 2 types :

  1. Static Constructor
  2. Instance Constructor
    • Default Constructor
      1. SystemDefined Constructor
      2. UserDefined Constructor
    • Copy Constructor
    • Parameterized Constructor
what is Constructor

Rules to Declare Constructor

  • Constructor name and class name both must be same
  • Constructor doesn't have any return type atleast void.
  • Constructor will get invoked immediately after creating object.

Static Constructor

  • Static Constructor declare with static Keywords.
  • Static Constructor is used to initialize the values for static variables.
  • Syntax :
       Class classname
       {
        static classname
         {
            ------
            ------
         }
       }
      
  • Static Constructor will invoked by CLR.

Constructor Example

using System;
 class A
  {
   static int x;
   static A()
    {
     x = 10;
     Console.WriteLine("I'm Static Constructor");
    }
   static void Main()
    {
     Console.WriteLine("I'm Main Method");
    }
  }

Note :


WhenEver we execute the above program.
  • CLR allocated memory for static variable on "STACK".
  • All the methods including Constructor will loading into "Method Area".
  • CLR will search for "Static Constructor" and it will load the "Static Constructor" in ""Execution Engine" and start execution. Static Constructor will initialize the values for "Static Variable"
  • CLR will search for "Static void Main" method and execute the code that was written within Main().

Output :
I'm static Constructor
I'm Main Method

Default Constructor

It is used to initialize default values for instances variables. Whenever we declare a class and if we not declare any constructor with in the class then compiler will declare "Default Constructor" and it will initialize default values for instance variable

 int        --  0
 float      --  0.0
 double     --  0.0
 string     --  null
 char       --  single space   

For Example :

using System;
 class A
  {
   int x;
   string s;
   double d;
   float r; 
   void Display()
    {
      Console.WriteLine(x);
      Console.WriteLine(s);
      Console.WriteLine(d);
      Console.WriteLine(r);
    }
   static void Main()
    {
      A a1 = new A();
        a1.Display(); 
    }
  }

Observation :

  1. WhenEver we compile the program csharp(CSC) compiler check any default constructor was declared or not. if the constructor was not declared than compiler will declare default constructor and the default values was initialized for instances variable.
  2. WhenEver we execute the program CLR will loads all the methods in Method Area. CLR will identify static void Main() and execute the code with in Main()
     A a1 = new A();
    
    1. New : is dynamic memory allocation operator which will create object and memory is allocated for instance variables.
    2. A() : Default Constructor is invoked and values are initialized for instance variables.
    3. A a1 : Reference Variable is created on "STACK".
    4. Reference Variable will refer to Object

UserDefined Default Constructor

It is used to pass user defined values instead of default values.

Example :


class Student
 {
  int sno;
  string sname;

   Student()
   {
    sno = 101;
    sname = "anil";
   }
   void Display()
   {
    Console.WriteLine(sno);
    Console.WriteLine(sname);
   }
   static void Main()
   {
     Student s1 = new  Student();
             s1.Display();
   }
 }

Copy Constructor

It is used to copy one Object value into another Object.

Example :


Using System;
 class Employee
  {
   int eno;
   string ename;

   Employee()
    {
     eno = 101;
     ename = "anil";
    }

   Employee(Employee e1)
    {
     eno = e1.eno;
     ename = e1.ename;
    }
 
   void Display()
    {
     Console.WriteLine(eno);
     Console.WriteLine(ename);
    }

   static void Main()
   {
     Employee e2 = new Employee();
              e2.Display();

     Employee e3 = new Employee();     
              e3.Display();
   }
  }

Parameterized Constructor

  • It is used to initialize different values for the different object.
  • At the time of declaring the constructor we have to declare the parameters. And at the time of creating object we have to pass values.
  • Syntax :
       class classname
        {
          classname(parameters)
          {
            -----
            ----- 
          }
        }
      
  • The no. of values that we pass must match with no. of parameters.
  • The order of values that we pass must match with order of parameters
  • The type of values that we pass must match with type of parameters

Example :


 class Customer
  {
   static string bankname;
   static string bankaddress;
   long accountno;
   string customername;
   double currentbalance;

  static Customer()
   {
    bankname = "SBI";
    bankaddress = "Hyderabad, Panjagutta";
   }
  
  Customer(long accno, string custname, double balance)
   {
    accountno = accno;
    customername = custname;
    currentbalance = balance;
   }

  static void DisplayBankData()
   {
     Console.WriteLine("Bank Details is : " + bankname + bankaddress);
   }

  void Deposit(double amt)
   {
     currentbalance = currentbalance + amt;
   }
  
  void Withdraw(double amt)
   {
     currentbalance = currentbalance - amt;
   }

  void PrintTransactionData()
   {
     Console.WriteLine( accno, custname, balance);
   }

  static void Main()
   {
    Customer c1 = new Customer(101, "anil", 5000);
    Customer c2 = new Customer(102, "arun", 7800);
             c1.Deposit(2500);
             c2.Deposit(5000);
             c1.Withdraw(500);
             c2.Withdraw(1500);
             c1.PrintTransactionData();
             c2.PrintTransactionData();
   }
  }
0 Komentar untuk "C# : Constructor"

Back To Top