Constructors
Learn how constructors initialize objects, including default, parameterized, and overloaded constructors.
What is a Constructor?
A constructor is a special method that runs automatically when an object is created with `new`. It shares the class's name and has no return type, and is typically used to set up initial values.
Parameterized Constructors
class Student{ public string Name; public int Age;
public Student(string name, int age) { Name = name; Age = age; }}
var student = new Student("Aarav", 20);Console.WriteLine($"{student.Name} is {student.Age}");Output
Click Run to see what this code prints.
Constructor Overloading
Like methods, constructors can be overloaded to support creating objects in different ways.
class Student{ public string Name; public int Age;
public Student(string name, int age) { Name = name; Age = age; }
public Student(string name) : this(name, 18) // calls the other constructor { }}The this Keyword
`this` refers to the current object instance. It's especially useful for disambiguating a field from a constructor parameter with the same name.
class Point{ public int X; public int Y;
public Point(int x, int y) { this.X = x; // this.X is the field, x is the parameter this.Y = y; }}FAQs
C# provides a free, parameterless default constructor automatically — but only if you don't define any constructor of your own.
Summary
- Constructors initialize an object when it's created.
- They can be overloaded to support different creation patterns.
- `this` refers to the current instance, useful for resolving naming conflicts.