CHASH Tutorial



C# CONSTRUCTORS


Constructors in C#

A constructor is a special method in a class that is automatically called when an object of the class is created. It is used to initialize objects.

Syntax of a Constructor

A constructor has the same name as the class and does not have a return type (not even void).

class Car
{
    public string brand;

    // Constructor
    public Car()
    {
        brand = "Default Brand";
        Console.WriteLine("Constructor called!");
    }
}
  

Using the Constructor

When an object is created, the constructor is automatically called:

class Program
{
    static void Main()
    {
        Car myCar = new Car();  // Constructor runs here
        Console.WriteLine(myCar.brand);  // Output: Default Brand
    }
}
  

Parameterized Constructor

Constructors can also take parameters to initialize fields with custom values.

class Car
{
    public string brand;

    // Constructor with parameter
    public Car(string carBrand)
    {
        brand = carBrand;
    }
}

class Program
{
    static void Main()
    {
        Car car1 = new Car("Honda");
        Car car2 = new Car("Toyota");

        Console.WriteLine(car1.brand);  // Output: Honda
        Console.WriteLine(car2.brand);  // Output: Toyota
    }
}
  

Default vs Parameterized Constructor

  • Default Constructor: No parameters
  • Parameterized Constructor: Accepts parameters for initialization
Key Points:
  • Constructors initialize objects when they are created
  • The constructor name must match the class name
  • Constructors do not have a return type
  • You can create multiple constructors with different parameters (constructor overloading)

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review