Constructors
Constructors
Section titled βConstructorsβWhat it means
Section titled βWhat it meansβ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.
Examples
Section titled βExamplesβ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 onepublic class Empty { }var e = new Empty(); // works -- implicit default constructorCommon mistake
Section titled βCommon mistakeβ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 onepublic class Person{ public string Name; public Person() { } public Person(string name) { Name = name; }}Quick practice
Section titled βQuick practiceβ-
What happens to the implicit parameterless constructor once you define any constructor yourself?
Answer
It disappears β you must explicitly add a parameterless constructor if you still wantnew MyClass()to work. -
What does
: this(name, 0)do in a constructorβs signature?Answer
Constructor chaining β it calls another constructor on the same class first, letting you reuse its setup logic instead of duplicating it. -
Can a class have more than one constructor?
Answer
Yes β as long as each has a different parameter list (constructor overloading), just like regular method overloading.