Complete C# Tutorial

Constructors in C# – Learn with Examples and Code

πŸ‘‹ Welcome to Constructors in C#!

Imagine you just bought a new smartphone πŸ“±. The moment you turn it on, it comes with pre-installed apps, default settings, and some initial configurations. You don’t have to set up everything manually – it just works!

In C#, constructors do the same thing! They automatically initialize objects when they are created. No extra effort is needed. Sounds cool, right? Let’s dive in and understand how they work!

πŸ” What is a Constructor in C#?

A constructor is a special method that runs automatically when an object is created. It initializes an object and sets default values.

Β 

πŸ’‘ Why Do We Need Constructors?

Without constructors, every time we create an object, we’d have to manually set values. That’s repetitive and boring! Constructors make coding easier by automating object initialization.

Β 

πŸ› οΈ Constructor Syntax:

				
					class ClassName  
{  
    public ClassName() // Constructor  
    {  
        // Initialization code here  
    }  
}
				
			

A constructor has:

βœ… The same name as the class
βœ… No return type (not even void)
βœ… Runs automatically when an object is created

πŸ” Simple Program

				
					using System;

class Person  
{
    public string Name;

    // Constructor
    public Person()  
    {  
        Name = "Unknown";  
        Console.WriteLine("A new person object is created!");
    }  
}

class Program  
{
    static void Main()  
    {
        Person p = new Person();  
        Console.WriteLine($"Person's Name: {p.Name}");  
    }  
}
				
			
πŸ“Œ Output:
				
					A new person object is created!  
Person's Name: Unknown  
				
			
πŸ” Explanation:

βœ… The constructor runs automatically when the Person object is created.
βœ… It initializes the Name property to "Unknown".
βœ… The message "A new person object is created!" is printed, showing that the constructor is working.

This is a basic example that helps you understand how constructors work in C#.

πŸ“ Example 1: A Simple Constructor in C#

				
					using System;

class BankAccount  
{
    public string AccountHolder;
    public double Balance;

    // Constructor
    public BankAccount()  
    {  
        AccountHolder = "Unknown";  
        Balance = 0.0;  
        Console.WriteLine("A new bank account has been created!");
    }  
}

class Program  
{
    static void Main()  
    {
        BankAccount account = new BankAccount();  
        Console.WriteLine($"Holder: {account.AccountHolder}, Balance: ${account.Balance}");  
    }  
}
				
			
πŸ“Œ Output:
				
					A new bank account has been created!  
Holder: Unknown, Balance: $0.0  
				
			
  • The constructor runs automatically when we create the object.
  • It sets default values without needing extra code.

πŸ“ Example 2: Using a Constructor to Initialize Values

Let’s say we want to initialize the account holder’s name while creating the object.

				
					using System;

class BankAccount  
{
    public string AccountHolder;
    public double Balance;

    // Constructor with a parameter
    public BankAccount(string name)  
    {  
        AccountHolder = name;  
        Balance = 0.0;  
    }  
}

class Program  
{
    static void Main()  
    {
        BankAccount myAccount = new BankAccount("Steven");  
        Console.WriteLine($"Holder: {myAccount.AccountHolder}, Balance: ${myAccount.Balance}");  
    }  
}
				
			
πŸ“Œ Output:
				
					Holder: Steven, Balance: $0.0  
				
			
  • Now, we can pass values to the constructor while creating the object.
  • The constructor automatically assigns the name.

πŸ“ Example 3: Constructor with Multiple Parameters

What if we want to set both name and balance at the time of account creation? Let’s modify our constructor.

				
					using System;

class BankAccount  
{
    public string AccountHolder;
    public double Balance;

    // Constructor with parameters
    public BankAccount(string name, double initialBalance)  
    {  
        AccountHolder = name;  
        Balance = initialBalance;  
    }  
}

class Program  
{
    static void Main()  
    {
        BankAccount myAccount = new BankAccount("Steven", 1000);  
        Console.WriteLine($"Holder: {myAccount.AccountHolder}, Balance: ${myAccount.Balance}");  
    }  
}
				
			
πŸ“Œ Output:
				
					Holder: Steven, Balance: $1000.0  
				
			
  • The constructor now accepts multiple values.
  • We initialize both name and balance at object creation.

πŸ’‘ Real-World Scenario: A Car Factory πŸš—

Think of a car factory. Every car needs:

βœ… A brand name
βœ… A model name
βœ… A price

Instead of setting these manually for each car, we use a constructor.

				
					using System;

class Car  
{
    public string Brand;
    public string Model;
    public double Price;

    // Constructor
    public Car(string brand, string model, double price)  
    {  
        Brand = brand;  
        Model = model;  
        Price = price;  
    }  
}

class Program  
{
    static void Main()  
    {
        Car myCar = new Car("Tesla", "Model S", 79999);  
        Console.WriteLine($"Car: {myCar.Brand} {myCar.Model}, Price: ${myCar.Price}");  
    }  
}
				
			
πŸ“Œ Output:
				
					Car: Tesla Model S, Price: $79999.0  
				
			
  • The constructor initializes the car details as soon as an object is created.
  • No need for extra code – everything happens automatically.

🎯 Key Takeaways

βœ”οΈ A constructor in C# is a special method that runs automatically when an object is created.
βœ”οΈ It initializes values and makes coding easier.
βœ”οΈ We can create parameterized constructors to pass values at object creation.
βœ”οΈ Constructors help in real-world scenarios like bank accounts, car factories, and product catalogs.

Β 

⏭️ Next What?

Now that you know what a constructor is, let’s take it a step further! In the next chapter, you’ll learn different types of constructors in C#.

Stay excited, and let’s keep learning! πŸš€

Leave a Comment

Share this Doc

Constructor

Or copy link