- Published on
Constructors in C#
- Authors
- Name
- Cristian Pique
Introduction
Constructors
in C#
are special methods that are used to initialize an object's state when it is created. They are called automatically when an object is instantiated, and can be used to set default values, perform calculations, or perform other tasks that need to be done before the object is used.
There are five types of constructors (at least as of the time this article was published) in C#:
- Default constructor
- Parameterized constructor
- Copy constructor
- Static constructor
- Private constructor
The first two are the two main types of constructors in C#: default
constructors and parameterized
constructors.
Default constructor
A default constructor is one that takes no arguments and is automatically provided by the compiler if no other constructors are defined. It can be explicitly defined in code, but if it is not, then the compiler will generate one automatically.
Here is an example of a simple class with a default constructor:
class MyClass
{
public MyClass()
{
Console.WriteLine("MyClass object created.");
}
}
In some bibliographies the default constructor is also called parameterless constructor.
Parameterized constructor
A parameterized constructor, on the other hand, takes one or more arguments and is used to initialize the object with specific values.
class MyClass
{
private int _x;
private int _y;
public MyClass(int x, int y)
{
_x = x;
_y = y;
}
}
Copy constructor
It's important to note that C# also provides a special type of constructor called a copy
constructor, which is used to create a new object that is a copy of an existing object. A copy constructor takes a single argument of the same type as the class, and is used to initialize the new object with the state of the existing object.
public class Article
{
public string name;
public string author;
public string title;
public Article()
{
}
// Copy constructor.
public Article(Article article)
{
name = article.name;
author = article.author;
title = article.title;
}
}
Static constructor
Static
constructors in C# are special methods that are used to initialize static
members of a class. They are only invoked once, regardless of how many instances of the class are created.
To create a static
constructor, you simply define a method with the same name as the class and the keyword static
. For example:
Copy code
class MyClass
{
static MyClass()
{
// Initialization code goes here
}
}
It's important to note that a static
constructor cannot have any access modifiers (such as public or private) or any parameters. Additionally, a static constructor cannot be called directly, it will only be invoked automatically by the runtime when the class is first loaded.
One common use case for a static
constructor is to initialize a static variable that is used throughout the class. For example, the following code uses a static constructor to initialize a static variable _random with a new instance of the Random class:
class MyClass
{
private static Random _random = new Random();
static MyClass()
{
_random = new Random();
}
}
Another use case is to perform some additional initialization that is required before any instance of the class is created.
Static constructors are also useful if you want to ensure that a particular piece of code is executed before anything else in the class, such as performing a security check, or initializing a shared resource.
Private constructor
In C#, a private
constructor is a constructor that is marked with the private
access modifier. This means that the constructor can only be called from within the class and cannot be used to create new instances of the class from outside the class.
There are a few use cases for private constructors. One common use case is for classes that have only static members and should not be instantiated. For example, a utility class that contains helper methods but should not be instantiated as an object. Another use case is for classes that implement the singleton pattern. The singleton pattern is a design pattern that ensures that a class has only one instance and provides a global point of access to that instance. A private constructor can be used to prevent external code from creating new instances of the singleton class.
Here is an example of a class that has a private constructor and should not be instantiated:
class Utility
{
private Utility()
{
}
public static void DoSomething()
{
// code here
}
}
And here is an example of a class that implements the singleton pattern using a private constructor:
class Singleton
{
private static Singleton _instance;
private Singleton()
{
}
public static Singleton GetInstance()
{
if (_instance == null)
{
_instance = new Singleton();
}
return _instance;
}
}
It's important to note that making the constructor private does not prevent the class from being inherited. A class with a private constructor can still be inherited, but the derived class cannot call the base class's private constructor.
this
, base
, and order of execution
In C#, we can also use the this
keyword to refer to the current instance of the class within the constructor. This is often used to call other constructors within the same class using the : this() syntax. T
The basic syntax for calling the constructor of a parent class from a derived class in C# is as follows:
class ChildClass : ParentClass
{
public ChildClass() : base()
{
// Child class constructor code
}
}
You can also pass parameters to the parent class constructor by including them after the base keyword, like this:
class ChildClass : ParentClass
{
public ChildClass(int x, int y) : base(x, y)
{
// Child class constructor code
}
}
It's important to note that the parent class constructor is always called before the child class constructor, regardless of whether it is explicitly called or not. This is known as the order of execution.
The order of execution for constructors is as follows:
- First, the base class's static constructors are called in the order of their declaration.
- Then, the base class's instance constructors are called, starting with the constructor that has the most parameters.
- Finally, the derived class's static and instance constructors are called in the same order as the base class's constructors.
It's also important to mention that if the parent class doesn't have a default constructor and the child class doesn't explicitly call the parent's constructor the code will not compile.
TL;DR
In conclusion, constructors are an important feature of C# that provide a way to initialize an object's state when it is created. They come in various forms like default, parameterized and copy constructors and can be used to set default values, perform calculations, or perform other tasks that need to be done before the object is used. If you do not provide one, a default parameterless constructor is provided automatically. A constructor can call another constructor in the same class, or a constructor of the parent class. Understanding and utilizing constructors is an important part of becoming proficient in C# programming.