C# Constructors

Last Updated on June 11, 2022
C# Constructors

C# Constructors

The constructors are the special method that can be called automatically when an object of a class is created. The constructors can be with or without parameters.

Note: The constructor’s name should match the class name. One class may have one or more than one constructor with different parameters signature.

Let’s see some examples of the C# constructors.

 
using System;

namespace ConsoleAppDemo
{

    class Computer {

        //Constructors
        public Computer()
        {
            Console.WriteLine("Default Constructor");
        }

        public Computer(int Id, string brand)
        {
            Console.WriteLine("Constructor with Parameter. Id: {0} and Brand: ",Id, brand);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            //Create an object
            Computer computer = new Computer(); //This will call default Constructors
            Computer computer1 = new Computer(5,"Lenovo"); //This will call parameterized Constructors

            Console.ReadKey();
        }
    }
}
    

Output:

Default Constructor
Parameter Constructor. Id: 5 and Brand: Lenovo