Understanding C# Constructors

Constructors in C# are special methods used to initialize objects. They have the same name as the class and are called automatically when an object is created.

Key Topics

Default Constructors

If no constructor is defined, C# provides a default constructor that initializes fields to their default values.

Example: Using the Default Constructor

public class Animal
{
    public string Name;
    public int Age;
}

class Program
{
    static void Main(string[] args)
    {
        Animal animal = new Animal();
        animal.Name = "Lion";
        animal.Age = 5;
        Console.WriteLine($"Animal: {animal.Name}, Age: {animal.Age}");
    }
}

Output:

Animal: Lion, Age: 5
                    

Explanation: Since no constructor is defined, the default constructor is used.

Parameterized Constructors

You can define constructors that take parameters to initialize fields when an object is created.

Example: Creating a Parameterized Constructor

public class Animal
{
    public string Name;
    public int Age;

    // Parameterized constructor
    public Animal(string name, int age)
    {
        Name = name;
        Age = age;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Animal animal = new Animal("Tiger", 4);
        Console.WriteLine($"Animal: {animal.Name}, Age: {animal.Age}");
    }
}

Output:

Animal: Tiger, Age: 4
                    

Explanation: The parameterized constructor allows setting the initial values of the fields when creating the object.

Constructor Overloading

You can have multiple constructors in a class with different parameters, allowing for different ways to create objects.

Example: Overloading Constructors

public class Animal
{
    public string Name;
    public int Age;

    // Default constructor
    public Animal()
    {
        Name = "Unknown";
        Age = 0;
    }

    // Parameterized constructor
    public Animal(string name, int age)
    {
        Name = name;
        Age = age;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Animal animal1 = new Animal();
        Animal animal2 = new Animal("Elephant", 10);
        Console.WriteLine($"Animal1: {animal1.Name}, Age: {animal1.Age}");
        Console.WriteLine($"Animal2: {animal2.Name}, Age: {animal2.Age}");
    }
}

Output:

Animal1: Unknown, Age: 0
Animal2: Elephant, Age: 10
                    

Explanation: Two constructors are defined. One sets default values, and the other accepts parameters. This allows flexibility when creating objects.

Key Takeaways

  • Constructors initialize objects when they are created.
  • You can have multiple constructors with different parameters (constructor overloading).
  • If no constructor is defined, a default constructor is provided.
  • Constructors have the same name as the class and no return type.