Constructors in C#

Introduction

In the programming language C#, constructors are designated methods that serve the purpose of initializing and generating objects of a given class. These methods are invoked upon the creation of an instance of the class. Constructors are identified by the identical name as the class and do not possess a return type. The following are the fundamental categories of constructors in C#.

Default Constructor in C#

The default constructor is a constructor that does not have any parameters. In the event that constructors are not provided in a class, C# will automatically generate a default constructor. The following is an illustration.

public class SampleClass
{
    // Default constructor
    public SampleClass()
    {
        // Initialization code here
    }
}

Parameterized Constructor in C#

A parameterized constructor is a constructor that accepts one or more parameters to initialize the object with specific values. It is possible to have multiple parameterized constructors with different parameter lists. The following is an example of a parameterized constructor.

public class SampleClass
{
    public int Value { get; set; }

    // Parameterized constructor
    public SampleClass(int value)
    {
        Value = value;
    }
}

Copy Constructor in C#

The copy constructor is a constructor that accepts an object of the same class as a parameter and initializes a new object with identical values. In C#, copy constructors are not inherently provided, but they can be implemented by the programmer. An illustrative example is presented below.

public class SampleClass
{
    public int Value { get; set; }

    // Copy constructor
    public SampleClass(SampleClass other)
    {
        Value = other.Value;
    }
}

Static Constructor in C#

A static constructor is employed to initialize static members of a class or execute a one-time setup for a class. Static constructors are invoked automatically and do not require any parameters. They are defined using the static keyword and have no access modifiers. Here is an illustration.

public class SampleClass
{
    public static int StaticValue { get; set; }

    // Static constructor
    static SampleClass()
    {
        StaticValue = 42;
    }
}

In order to instantiate a class and utilize its constructors, the following steps can be undertaken.

// Using the default constructor
SampleClass obj1 = new SampleClass(); 

// Using the parameterized constructor
SampleClass obj2 = new SampleClass(10); 

// Using the copy constructor
SampleClass obj3 = new SampleClass(obj2); 

Conclusion

Constructors enable the establishment of the initial state of objects during their creation, rendering them a crucial component of object-oriented programming in C#.


Similar Articles