In C#, a constructor is a special method that is automatically called when an object of a class is created. It is mainly used to initialize objects and set default or custom values for class members.
A constructor has the same name as the class and does not have a return type (not even void).
It runs automatically when we create an object using the new keyword.
A default constructor does not take any parameters. It assigns default values.
class Student
{
public string name;
public int age;
// Default Constructor
public Student()
{
name = "Unknown";
age = 0;
}
}
class Program
{
static void Main()
{
Student s1 = new Student();
Console.WriteLine(s1.name);
Console.WriteLine(s1.age);
}
}
A parameterized constructor accepts values to initialize objects with custom data.
class Student
{
public string name;
public int age;
// Parameterized Constructor
public Student(string n, int a)
{
name = n;
age = a;
}
}
class Program
{
static void Main()
{
Student s1 = new Student("Rahul", 20);
Student s2 = new Student("Amit", 22);
Console.WriteLine(s1.name + " " + s1.age);
Console.WriteLine(s2.name + " " + s2.age);
}
}
Constructor overloading means having multiple constructors with different parameters in the same class.
class Student
{
public string name;
public int age;
public Student()
{
name = "No Name";
age = 0;
}
public Student(string n)
{
name = n;
age = 0;
}
public Student(string n, int a)
{
name = n;
age = a;
}
}
using System;
class Car
{
public string brand;
public int year;
// Constructor
public Car(string b, int y)
{
brand = b;
year = y;
}
public void Show()
{
Console.WriteLine($"Car Brand: {brand}, Year: {year}");
}
}
class Program
{
static void Main()
{
Car c1 = new Car("Toyota", 2020);
Car c2 = new Car("Honda", 2022);
c1.Show();
c2.Show();
}
}
Constructors are an important part of C# classes. They make object creation easy, clean, and efficient by automatically initializing values.