Instance constructors in C# Part 1

In this article we will learn about  Instance constructors in C#.
  • 5805

Introduction

Constructor is a special method of the class that will be invoked automatically when an instance of the class is created.

Instance constructors 

There are four types of instance constructors in C# language.

  • Default Constructor

  • Parameterized Constructor

  • Copy Constructor

  • Private Constructor

Default constructor

A constructor that has no parameters is called the default constructor in C#. Each class has a default constructor. Default constructor is used when we want to initialize values of class members. Constructor has same name as class name.

Syntax

 

public classname()

{

}

Example

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace DefaultConstractor

{

    class Rahul

    {

        int x,y;

        public Rahul()   //default contructor

        {

            x = 10;

            y = 11;

        }

 

        public static void Main()

        {

            Rahul obj = new Rahul(); //an object is created , constructor is called

            Console.WriteLine(obj.x);

            Console.WriteLine(obj.y);

            Console.ReadLine();

        }

    }

}

 

 The output of following program

 Clipboard185.jpg

Parameterized Constructor

A constructor that has at least one parameter is called the Parameterized Constructor in C#. Parameterized Constructor is used when we want to initialize each instance of the class to different values.

Syntax

 

public classname(parameter x)

{

}

 

Example

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace Constructor

{

    class Rahul

    {

      public  int P, Q;

      public Rahul(int x, int y)  // decalaring Paremetrized Constructor with passing x,y parameter

        {

            P = x;

            Q = y;

        }

   }

    class MainClass

    {

        static void Main()

        {

            Rahul v = new Rahul(10, 11);   // Creating object of Parameterized Constructor and passing values  

            Console.WriteLine("P is =" + v.P );

            Console.WriteLine("Q is =" + v.Q);

            Console.ReadLine();

        }

    }

}

 

The output of following program


Clipboard186.jpg


© 2020 DotNetHeaven. All rights reserved.