C# Constructor

What is Constructor in c#?

  1. Constructor is a special type of function.
  2. Constructor must be set the public access modifier.
  3. Constructor don't have static keyword.
  4. Constructor name must be the same name of the class name.
  5. When you create class's object then automatically called the constructor.

Types Of Constructor

Basically, Constructor are three types such as

  1. Non Parameterized Constructor
  2. Parameterized Constructor
  3. Copy Constructor

Example Of Non Parameterized Constructor

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Array
{
    class Program
    {
        
        public Program()  //Non Parameterized Constructor created
        {
            Console.WriteLine("Constructor Are Called");
        }
        static void Main(string[] args)
        {
            Program p1 = new Program();  //Non Parameterized Constructor are called
            Console.ReadLine();
        }
    }
}

Output

Constructor Are Called

Example Of Parameterized Constructor

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Array
{
    class Program
    {
        
        public Program(string input)  //Parameterized Constructor created
        {
            Console.WriteLine(input);
        }
        static void Main(string[] args)
        {
            Program p1 = new Program("Hello GuriaSoft");  //Parameterized Constructor are called
            Console.ReadLine();          
        }
    }
}

Output

Hello GuriaSoft

Example Of Copy Constructor

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Array
{
    class Program
    {
       private int a,b;
       public Program(int a1, int b1)  
       {
           a = a1;
           b = b1;
       }
        public Program( Program p2)  //Copy Constructor created
        {
            a = p2.a;
            b = p2.b;
            int s = a + b;
            Console.WriteLine("Copy Constructor Called and Result = "+s);
        }
        static void Main(string[] args)
        {
            Program p1 = new Program(10,20);
            Program p2 = new Program(p1) ;  //Here Called Copy Constructor
            Console.ReadLine();
        }
    }
}

Output

Copy Constructor Called and Result = 30


Write a comment


Name Email Message