Introduction to Constructors in C#

C# programming tutorials

A class in C# contains both data members and member functions or methods. To initialize the data members of a class, programmers can use constructors. This programming tutorial talks about constructors in C#, their benefits, and how they can be used through code examples.

Before reading further, we have a great tutorial covering Object Oriented Programming for Beginners, if you need a refresher on basic OOP principles. Our guide to Classes in C# is also a great introduction to the concept of classes.

What is a Constructor n C#?

A constructor is a special type of method of a class that has the same name as the class name and that gets called automatically when the class is instantiated. A constructor should be declared in the same class as its name and have no return type.

There can be multiple constructors for a class, but only one will be called at a time based on the parameter list used when creating an object. By default, the compiler provides a constructor without parameters if no constructor is written by the user.

We call this constructor the default constructor. The default constructor will only be available if you do not write any constructors in your class.

It should be noted that a constructor cannot be virtual, but programmers can have virtual destructors for a class. Constructors of class cannot return any value. A class can have static, non-static, parameterized and non-parametrized constructors.

The non-parameterized constructor of a class is the default constructor which is provided by the runtime implicitly or, you can write your own.

The following code example shows the syntax for creating a constructor for a class in C#:

[modifier] name (parameters)
{
 // Your code goes here
}

Read: Top Task Management Software for Developers

Benefits and Use Cases of Constructors in C#

In C#, constructors are often used to set default values for fields, such as initializing a field to 0 or null. The purpose of a constructor is to ensure that all of the data members of a class are properly initialized before the program begins using them.

Constructors can also be used to set default values for data members and perform other tasks that need to be done when an object is created.

Constructors can also be used to perform other actions when an object is created, such as opening a file or establishing a database connection. One advantage of using constructors is that they make code more readable by self-documenting what needs to happen when an object is created.

Another advantage is that constructors can ensure that objects are always created in a valid state by initializing fields to appropriate values before performing any other operations.

Constructor Overloading in C#

When a class has multiple constructors, each differing in their signatures, we may say that the constructors of the class are overloaded. Constructor overloading is a mechanism of having more than one constructor with different parameters lists in a single class.

The idea behind constructor overloading is to provide the user different ways of creating an object depending on what information they have. For example, let’s say we have a class that represents a Rectangle.

We could have two constructors: one that takes the width and height as parameters, and another that takes the x and y coordinates of the top-left corner, along with the width and height.

The following code example illustrates the Rectangle class and how to perform constructor overloading in C#:

public class Rectangle
{
    public int Width { get; set; }
    public int Height { get; set; }
    public Point TopLeft { get; set; }    
    public Rectangle(int width, int height) // Accepts width and height 
    //as parameters
    {
        Width = width; Height = height;
    }    
    public Rectangle(int width, int height, Point topLeft) // Accepts width 
    //& height and the top-left corner as parameters
    {
        TopLeft = topLeft; 
        Width = width; 
        Height = height;
    }
}

In the above C# code example, we can see how having multiple constructors can be useful. If all we know about our rectangle is its width and height, then we can use the first constructor. But, if we also know the location of the rectangle’s top-left corner, then we can use the second constructor.

You can learn more about C# overloading in our tutorial: How to Overload Methods in C#.

Static Constructors in C#

In C#, a static constructor is a constructor that can be declared in a static or non-static class, is called only once, and does not accept any parameters. Using static constructors, you can initialize the static members of a class. Unlike other constructors, static constructors do not have an instance parameter. That is because they are only called before the first instance is created.

When a class is created, or any static members of the class are accessed the first time, the static constructor of the class is called automatically. Static constructors only get called once per app domain. Developers can have one – and only one – static constructor for a class. In other words, static constructors of a class cannot be overloaded.

The following code example shows how to declare a static constructor in a non-static class in C#:

public class MyNonStaticClass
{
    static MyNonStaticClass()
    {
        Console.WriteLine("Inside a static constructor.");
    }
    public MyNonStaticClass()
    {
        Console.WriteLine("Inside an instance constructor.");
    }
}

Here is a code example showing how to create a static constructor inside a static class in C#:

public static class MyStaticClass
{
    static MyStaticClass()
    {
        Console.WriteLine("Inside a static constructor.");
    }
}

Note that a static class cannot have any instance members in it.

You can learn more about class members in our tutorial: Class Members in C#.

Final Thoughts on C# Constructors

While constructors can be overloaded, you cannot override constructors, since they cannot be inherited. There may be a static constructor in the class, however, there can never be a static destructor in the class.

Joydip Kanjilal
Joydip Kanjilal
A Microsoft Most Valuable Professional in ASP.NET, Speaker, and Author of several books and articles. More than 25 years of experience in IT with more than 18 years in Microsoft .NET and its related technologies. He was selected as a Community Credit Winner at http://www.community-credit.com several times. He has authored 8 books and more than 500 articles in some of the most reputed sites worldwide including MSDN, Info World, CodeMag, Tech Beacon, Tech Target, Developer, CodeGuru, and more.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read