C# Constructors

Updated on     Kisan Patel

A constructor is the first method that is executed when an instance of a class is created. It has the same name as its containing class. It never returns any value. It must made public.

The constructor contains initialization code for each object. For example, assigning default values to the field or variables.

class Person
{
    public Person()
    {
         Console.WriteLine("Constructor called...");
    }
}

In addition, you can also write constructors to accept arguments.

A constructor that accepts arguments is called a parameterized constructor.

class Person
{
    public Person(int age)
    {
        Console.WriteLine("Parameterized Constructor called...");
        Console.WriteLine("Your age is : " + age);
    }
}

Let’s take one example to understand using constructors in C# programming language.

using System;

namespace ConsoleApp
{
    class Person
    {
        public Person()
        {
            Console.WriteLine("Constructor called...");
        }

        public Person(int age)
        {
            Console.WriteLine("Parameterized Constructor called...");
            Console.WriteLine("Your age is : " + age);
        }
    }

    class PropertyTester
    {
        public static void Main(string[] args)
        {
            Person obj = new Person();
            Person objNew = new Person(24);
        }
    }
}

The output of the above C# program…

c-sharp-constructors-demo

In above example, there are two constructors of Person class are used, the first without any parameters and the second with one parameter.


C#

Leave a Reply