Skip to content

Constructors

A constructor is a special method that runs automatically when an object is created with new, used to set up its initial state. It shares the class’s name and has no return type. A class can have multiple constructors with different parameters (overloading), and one constructor can call another with this(...) to avoid duplicating setup logic.

public class Person
{
public string Name { get; }
public int Age { get; }
public Person(string name, int age)
{
Name = name;
Age = age;
}
public Person(string name) : this(name, 0) // calls the constructor above
{
}
}
var alice = new Person("Alice", 30);
var baby = new Person("Baby"); // Age defaults to 0 via constructor chaining
// If a class defines NO constructor at all, C# provides a free parameterless one
public class Empty { }
var e = new Empty(); // works -- implicit default constructor

Defining a custom constructor with parameters and then being surprised that new MyClass() (parameterless) no longer compiles β€” once you define any constructor, the compiler-provided implicit parameterless constructor disappears.

public class Person
{
public string Name;
public Person(string name) { Name = name; }
}
var p = new Person(); // Error: no argument given that corresponds to the required parameter 'name'
// Fix: explicitly add a parameterless constructor if you still need one
public class Person
{
public string Name;
public Person() { }
public Person(string name) { Name = name; }
}
  1. What happens to the implicit parameterless constructor once you define any constructor yourself?

    AnswerIt disappears β€” you must explicitly add a parameterless constructor if you still want new MyClass() to work.
  2. What does : this(name, 0) do in a constructor’s signature?

    AnswerConstructor chaining β€” it calls another constructor on the same class first, letting you reuse its setup logic instead of duplicating it.
  3. Can a class have more than one constructor?

    AnswerYes β€” as long as each has a different parameter list (constructor overloading), just like regular method overloading.