Constructors are special methods in C# used to initialize objects. They allow you to set up the initial state of an object when it's created, ensuring that necessary data is provided and properly initialized.
Constructors share the same name as the class and don’t have a return type.
In this tutorial, we’ll cover:
1. Basics of Constructors
A constructor is automatically called when an object of a class is created. If no constructor is defined, C# provides a default constructor. Constructors have the same name as the class, no return type, and are typically used to initialize fields or properties.
Example: Basic Constructor
using System; public class Person { public string Name; public int Age; // Constructor public Person(string name, int age) { Name = name; Age = age; } public void DisplayInfo() { Console.WriteLine($"Name: {Name}, Age: {Age}"); } } public class ConstructorExample { public static void Main() { Person person = new Person("John", 25); // Creates an object and calls the constructor person.DisplayInfo(); } }
In this example:
- The Person class has a constructor that takes name and age as parameters to initialize its fields.
- When new Person(“John”, 25) is called, the constructor initializes the Name and Age fields.
Output:
Name: John, Age: 25
2. Types of Constructors
C# supports several types of constructors:
a. Default Constructor
A default constructor has no parameters. It’s provided automatically if no other constructor is defined.
Example: Default Constructor
using System; public class Car { public string Model; public int Year; // Default Constructor public Car() { Model = "Unknown"; Year = 2022; } public void DisplayInfo() { Console.WriteLine($"Model: {Model}, Year: {Year}"); } } public class DefaultConstructorExample { public static void Main() { Car car = new Car(); // Calls the default constructor car.DisplayInfo(); } }
In this example:
- Car has a default constructor that initializes Model and Year with default values.
Output:
Model: Unknown, Year: 2022
b. Parameterized Constructor
A parameterized constructor allows you to pass parameters to initialize fields with specific values.
Example: Parameterized Constructor
using System; public class Book { public string Title; public string Author; // Parameterized Constructor public Book(string title, string author) { Title = title; Author = author; } public void DisplayInfo() { Console.WriteLine($"Title: {Title}, Author: {Author}"); } } public class ParameterizedConstructorExample { public static void Main() { Book book = new Book("The Catcher in the Rye", "J.D. Salinger"); book.DisplayInfo(); } }
Output:
Title: The Catcher in the Rye, Author: J.D. Salinger
c. Copy Constructor
A copy constructor creates a new object by copying the data of another object of the same type.
Example: Copy Constructor
using System; public class Rectangle { public int Width; public int Height; // Parameterized Constructor public Rectangle(int width, int height) { Width = width; Height = height; } // Copy Constructor public Rectangle(Rectangle rectangle) { Width = rectangle.Width; Height = rectangle.Height; } public void DisplayInfo() { Console.WriteLine($"Width: {Width}, Height: {Height}"); } } public class CopyConstructorExample { public static void Main() { Rectangle rect1 = new Rectangle(10, 20); Rectangle rect2 = new Rectangle(rect1); // Uses copy constructor rect1.DisplayInfo(); rect2.DisplayInfo(); } }
In this example:
- Rectangle has a copy constructor that copies the Width and Height from another Rectangle object.
Output:
Width: 10, Height: 20 Width: 10, Height: 20
d. Static Constructor
A static constructor is used to initialize static fields or perform tasks that need to be executed only once for the entire class. It cannot have parameters and is called automatically before any static members are accessed.
Example: Static Constructor
using System; public class Logger { public static string LogLevel; // Static Constructor static Logger() { LogLevel = "Info"; Console.WriteLine("Static constructor called."); } public static void Log(string message) { Console.WriteLine($"[{LogLevel}] {message}"); } } public class StaticConstructorExample { public static void Main() { Logger.Log("This is a log message."); } }
In this example:
- The static constructor sets LogLevel to “Info”.
- It only runs once, even if multiple objects of the class are created.
Output:
Static constructor called. [Info] This is a log message.
3. Using this Keyword in Constructors
The this keyword is used to refer to the current instance of a class. It’s helpful when parameter names conflict with field names.
Example: Using this Keyword
using System; public class Product { private string name; private decimal price; public Product(string name, decimal price) { this.name = name; // Using 'this' to distinguish between parameter and field this.price = price; } public void DisplayInfo() { Console.WriteLine($"Product: {name}, Price: ${price}"); } } public class ThisKeywordExample { public static void Main() { Product product = new Product("Laptop", 999.99m); product.DisplayInfo(); } }
In this example:
- this.name refers to the instance variable name, differentiating it from the parameter name.
Output:
Product: Laptop, Price: $999.99
4. Constructor Chaining
Constructor chaining allows one constructor to call another within the same class. It’s useful when you have multiple constructors and want to reuse initialization code.
Example: Constructor Chaining
using System; public class Employee { public string Name; public int Age; public string Position; // Constructor with name and age public Employee(string name, int age) : this(name, age, "Unassigned") { } // Constructor with name, age, and position public Employee(string name, int age, string position) { Name = name; Age = age; Position = position; } public void DisplayInfo() { Console.WriteLine($"Name: {Name}, Age: {Age}, Position: {Position}"); } } public class ConstructorChainingExample { public static void Main() { Employee emp1 = new Employee("Alice", 30); Employee emp2 = new Employee("Bob", 25, "Developer"); emp1.DisplayInfo(); emp2.DisplayInfo(); } }
Explanation:
- The constructor Employee(string name, int age) calls the more detailed constructor to set a default Position of “Unassigned.”
Output:
Name: Alice, Age: 30, Position: Unassigned Name: Bob, Age: 25, Position: Developer
5. Practical Examples of Constructors
Example 1: Bank Account with Initial Balance
using System; public class BankAccount { public decimal Balance { get; private set; } public BankAccount(decimal initialBalance) { Balance = initialBalance; } public void Deposit(decimal amount) { Balance += amount; } public void DisplayBalance() { Console.WriteLine("Current Balance: $" + Balance); } } public class BankAccountExample { public static void Main() { BankAccount account = new BankAccount(1000); // Initializes balance with 1000 account.Deposit(500); account.DisplayBalance(); } }
Output:
Current Balance: $1500
Example 2: Book with Optional Author
using System; public class Book { public string Title { get; private set; } public string Author { get; private set; } public Book(string title) : this(title, "Unknown") { } public Book(string title, string author) { Title = title; Author = author; } public void DisplayInfo() { Console.WriteLine($"Title: {Title}, Author: {Author}"); } } public class BookExample { public static void Main() { Book book1 = new Book("1984"); Book book2 = new Book("The Great Gatsby", " F. Scott Fitzgerald"); book1.DisplayInfo(); book2.DisplayInfo(); } }
Output:
Title: 1984, Author: Unknown Title: The Great Gatsby, Author: F. Scott Fitzgerald
Summary
Constructors in C# are powerful tools for initializing objects and setting up their state.
Here’s a recap of the key concepts:
- Default Constructor: Provided automatically if no other constructor is defined.
- Parameterized Constructor: Allows setting initial values via parameters.
- Copy Constructor: Creates a new object by copying values from another object.
- Static Constructor: Initializes static fields and is called once for the entire class.
- this Keyword: Refers to the current instance and aids in constructor chaining.
- Constructor Chaining: Reuses initialization code between multiple constructors.
Constructors make objects in C# more flexible, ensuring data consistency and streamlining initialization, which improves the quality and maintainability of your code.