How to Create and Use Constructors in C#

0
598
How to Create and Use Constructors in C#

A constructor is a special type of method in a class or struct that is called when an instance of the class or struct is created. It is typically used to initialize the new object’s fields and perform any other necessary setup.

Constructors have the same name as the class or struct and do not have a return type. They are often defined with the same access modifier as the class or struct (e.g. public or private).

In C#, a constructor is a method called when a class instance is created. It can be used to initialize the new object’s fields and perform any other necessary setup.

Here is an example of a simple custom class with a constructor:

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

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

To use this constructor, you can create a new instance of the Person a class like this:

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

This will create a new Person object with the name “John” and the age of 30.

You can also create constructors with different parameters, or no parameters at all. For example:

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

    // Constructor with no parameters
    public Person()
    {
        Name = "";
        Age = 0;
    }

    // Constructor with only a name parameter
    public Person(string name)
    {
        Name = name;
        Age = 0;
    }

    // Constructor with both name and age parameters
    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
}

You can then use these constructors like this:

Person p1 = new Person();
Person p2 = new Person("Jane");
Person p3 = new Person("Bob", 40);

Note that in C#, every class has a default constructor that is automatically created if you don’t specify any constructors for your class. This default constructor has no parameters and does not perform any initialization.

However, if you define any constructors for your class, the default constructor will not be created automatically, and you will need to explain it yourself if you want to have it available.