Constructors in C#

C#.Net Constructors: Learn, what is the constructor, how they proclaimed, characterized and their properties with an example in C#.Net?

Constructors are a unique sort of strategies in C#, which is naturally summoned when an article is being made. It is fundamentally used to:

  1. To introduce information individually from class.
  2. To designate memory for information part.

There are the following properties of constructor in C#:

  1. The constructor has a similar name to the class name. It is case touchy.
  2. The constructor doesn’t have return type.
  3. We can over-burden constructor, it implies we can make more than one constructor of the class.
  4. We can utilize default contention in constructor.
  5. It must be an open sort.

Think about the program:

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

namespace ConsoleApplication1
{
    class EMP
    {
        private string name ;
        private int age     ;
        private int salary  ;

		//constructor
        public EMP()
        {
            name   = "Kishan";
            age    = 21     ;
            salary = 35400  ;
        }
        public void setEmp(string name, int a = 18, int salary = 20000) 
        {
            this.name   = name      ;
            this.age    = a       ;
            this.salary = salary    ;


        }

        public void printEmp()
        {
            Console.WriteLine("\nEmployee Record: ");
            Console.WriteLine("\tName  : " + name   );
            Console.WriteLine("\tAge   : " + age    );
            Console.WriteLine("\tSalary: " + salary );

        }
		
    }

    class Program
    {
        static void Main()
        {
            EMP E0 = new EMP();

            E0.printEmp();

            EMP E1 = new EMP();

            E1.setEmp("Durgesh", salary: 38500);
            E1.printEmp();

            EMP E2 = new EMP();

            E2.setEmp("Aakash", a:33);
            E2.printEmp();
        }
    }
}

Output

Employee Record:
        Name  : Kishan
        Age   : 21
        Salary: 35400

Employee Record:
        Name  : Durgesh
        Age   : 18
        Salary: 38500

Employee Record:
        Name  : Aakash
        Age   : 33
        Salary: 20000

In the above example EMP () strategy is constructor, it introduces an object when the article makes.

Typically Constructors are following sort:

  • Default Constructor or Zero contention constructor
  • Parameterized constructor
  • Duplicate constructor

Leave a Comment

error: Alert: Content is protected!!