C# Constructors - Complete Guide
Introduction to Constructors
Constructors in C# are special methods used to initialize objects of a class. They have the same name as the class and do not declare a return type. Constructors are executed automatically when an object is created using the 'new' keyword.
C# supports several types of constructors, such as default constructors, parameterized constructors, static constructors, copy constructors, and private constructors. Each type is designed for specific initialization needs.
Types of Constructors
The following example demonstrates different constructor types in C#:
Example
using System;
namespace ConstructorsExample
{
public class Car
{
// Properties
public string Model { get; set; }
public int Year { get; set; }
// Default constructor
public Car()
{
Model = "Unknown";
Year = DateTime.Now.Year;
}
// Parameterized constructor
public Car(string model, int year)
{
Model = model;
Year = year;
}
// Copy constructor
public Car(Car otherCar)
{
Model = otherCar.Model;
Year = otherCar.Year;
}
// Static constructor
static Car()
{
Console.WriteLine("Static constructor called - Car class initialized");
}
// Method to display car information
public void DisplayInfo()
{
Console.WriteLine($"Model: {Model}, Year: {Year}");
}
}
class Program
{
static void Main(string[] args)
{
// Default constructor
Car car1 = new Car();
car1.DisplayInfo();
// Parameterized constructor
Car car2 = new Car("Toyota Camry", 2022);
car2.DisplayInfo();
// Copy constructor
Car car3 = new Car(car2);
car3.DisplayInfo();
// Object initializer syntax
Car car4 = new Car
{
Model = "Honda Civic",
Year = 2023
};
car4.DisplayInfo();
}
}
}
Output
Static constructor called - Car class initialized Model: Unknown, Year: 2023 Model: Toyota Camry, Year: 2022 Model: Toyota Camry, Year: 2022 Model: Honda Civic, Year: 2023