Light Mode Image

C# Constructor

In C#, a constructor is a special method that is called when an object is created from a class.

 

It is used to initialize the object's state and perform any necessary setup. Constructors have the same name as the class and do not have a return type. Here's a basic example of a constructor in C#:

 

public class MyClass
{
    // Default constructor (parameterless)
    public MyClass()
    {
        // Initialization code goes here
    }

    // Parameterized constructor
    public MyClass(int initialValue)
    {
        // Initialization code with a parameter goes here
    }
}

 

In this example, there are two constructors:

 

1. The default constructor (public MyClass()):

This constructor has no parameters and is called when an object of the class is created without providing any specific values.

 

2. The parameterized constructor (public MyClass(int initialValue)):

This constructor takes a parameter (initialValue) and can be used when you want to initialize the object with specific values at the time of creation.

 

You can create an object of the class and call the constructors like this:

 

MyClass obj1 = new MyClass();               // Calls the default constructor
MyClass obj2 = new MyClass(42);             // Calls the parameterized constructor

 

Constructors play a crucial role in setting up the initial state of objects and are often used to perform tasks such as initializing fields, setting default values, or connecting to resources.