Constructors
Part of the Object Oriented Programming section of Coddy's C# journey — lesson 7 of 70.
A constructor is a special method that runs when you create an object. It initializes the object's properties and fields.
Default constructor with no parameters
public class Book
{
public string Title { get; set; }
public string Author { get; set; }
// Default constructor
public Book()
{
Title = "Unknown";
Author = "Unknown";
}
}Parameterized constructor
public class Book
{
public string Title { get; set; }
public string Author { get; set; }
// Constructor with parameters
public Book(string title, string author)
{
Title = title;
Author = author;
}
}Constructor overloading - multiple constructors
public class Book
{
public string Title { get; set; }
public string Author { get; set; }
public int Pages { get; set; }
// Constructor with two parameters
public Book(string title, string author)
{
Title = title;
Author = author;
Pages = 0;
}
// Constructor with three parameters
public Book(string title, string author, int pages)
{
Title = title;
Author = author;
Pages = pages;
}
}Constructor chaining with this
public class Book
{
public string Title { get; set; }
public string Author { get; set; }
public int Pages { get; set; }
// Main constructor
public Book(string title, string author, int pages)
{
Title = title;
Author = author;
Pages = pages;
}
// Calls the main constructor with default pages
public Book(string title, string author) : this(title, author, 0)
{
}
}Creating objects with different constructors
Book book1 = new Book("1984", "George Orwell");
Book book2 = new Book("Harry Potter", "J.K. Rowling", 500);Constructors have the same name as the class and no return type. They run automatically when you use the new keyword. You can have multiple constructors with different parameters (overloading).
Challenge
MediumCreate three constructors for the Product class using constructor overloading and chaining:
- A constructor with 3 parameters: name, price, and stock
- A constructor with 2 parameters: name and price (stock defaults to 0)
- A default constructor with no parameters (name = "Unknown", price = 0, stock = 0)
Use constructor chaining with this to avoid code duplication.
Cheat sheet
A constructor is a special method that runs when you create an object. It initializes the object's properties.
Constructors have the same name as the class and no return type. They run automatically when you use the new keyword.
Default constructor with no parameters:
public class Book
{
public string Title { get; set; }
public Book()
{
Title = "Unknown";
}
}Parameterized constructor:
public class Book
{
public string Title { get; set; }
public string Author { get; set; }
public Book(string title, string author)
{
Title = title;
Author = author;
}
}Constructor overloading - multiple constructors with different parameters:
public class Book
{
public string Title { get; set; }
public int Pages { get; set; }
public Book(string title)
{
Title = title;
Pages = 0;
}
public Book(string title, int pages)
{
Title = title;
Pages = pages;
}
}Constructor chaining with this to avoid code duplication:
public class Book
{
public string Title { get; set; }
public int Pages { get; set; }
public Book(string title, int pages)
{
Title = title;
Pages = pages;
}
public Book(string title) : this(title, 0)
{
}
}Creating objects with different constructors:
Book book1 = new Book("1984", "George Orwell");
Book book2 = new Book("Harry Potter", "J.K. Rowling", 500);Try it yourself
using System;
class Program
{
static void Main()
{
string name = Console.ReadLine();
decimal price = decimal.Parse(Console.ReadLine());
int stock = int.Parse(Console.ReadLine());
Product product1 = new Product(name, price, stock);
Product product2 = new Product();
Product product3 = new Product("Keyboard", 79.99m);
Console.WriteLine($"Product 1: {product1.Name} - ${product1.Price} (Stock: {product1.Stock})");
Console.WriteLine($"Product 2: {product2.Name} - ${product2.Price} (Stock: {product2.Stock})");
Console.WriteLine($"Product 3: {product3.Name} - ${product3.Price} (Stock: {product3.Stock})");
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesNamespaces & DirectivesIntro to Classes & ObjectsThe 'this' KeywordMethods and ParametersFields vs PropertiesConstructorsObject InitializersRecap - Simple Calculator4Inheritance
Basic Inheritance (:) SyntaxThe 'base' KeywordVirtual & Override KeywordsSealed ClassesThe 'object' Base ClassRecap - Employee Hierarchy7Advanced Features
Operator OverloadingIndexers (this[])ToString() OverrideExtension MethodsRecap - Custom List2Properties & Static Members
Auto-Implemented PropertiesRead/Write-Only PropertiesStatic Fields & MethodsStatic ClassesExpression-Bodied Members5Polymorphism & Interfaces
Compile vs Runtime PolyInterface vs Abstract ClassMultiple InterfacesExplicit InterfacesUpcasting & DowncastingRecap - Shape Calculator