Constructor Function

Lesson 26
Author : Afrixi
Last Updated : February, 2023
C# - Programming Language
This course covers the basics of programming in C#. Work your way through the videos/articles and I'll teach you everything you need to know to start your programming journey!

A constructor is a special method that is automatically called when an object of a class is created. Its purpose is to initialize the object’s state by setting its properties and any other necessary setup.

In C#, a constructor method has the same name as the class and does not have a return type. Here is an example of a constructor for a class called Person:

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
}

In this example, the Person class has a constructor that takes two parameters: name and age. The constructor sets the Name and Age properties of the object being created.

We can create a new Person object and pass in values for the name and age parameters like this:

Person person = new Person("John", 30);

This creates a new Person object with the Name property set to “John” and the Age property set to 30.

Constructors can also be overloaded, which means there can be multiple constructors with different parameter lists. Here’s an example of a Person class with two constructors:

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    public Person()
    {
        Name = "Unknown";
        Age = 0;
    }

    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
}

In this example, we have a default constructor with no parameters that sets the Name property to “Unknown” and the Age property to 0. We also have a constructor that takes the name and age parameters and sets the Name and Age properties accordingly.

We can create a new Person object using either constructor:

Person person1 = new Person(); // uses default constructor
Person person2 = new Person("Jane", 25); // uses parameterized constructor