C# Constructors

Introduction

A constructor is a special method in a class that is called when an object of the class is created. Constructors are used to initialize the object’s data members and allocate resources. In C#, constructors have the same name as the class and do not have a return type. They can be overloaded to provide different ways of initializing objects.

Types of Constructors

  1. Default Constructor
  2. Parameterized Constructor
  3. Copy Constructor
  4. Static Constructor
  5. Private Constructor

1. Default Constructor

A default constructor is a constructor that does not take any parameters. If no constructors are defined in a class, the compiler automatically provides a default constructor.

Syntax

public class ClassName
{
    // Default constructor
    public ClassName()
    {
        // Initialization code
    }
}

Example

using System;

namespace ConstructorsExample
{
    public class Car
    {
        public string Model { get; set; }
        public string Color { get; set; }

        // Default constructor
        public Car()
        {
            Model = "Unknown";
            Color = "Unknown";
        }

        public void DisplayInfo()
        {
            Console.WriteLine($"Model: {Model}, Color: {Color}");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Car car = new Car();
            car.DisplayInfo();
        }
    }
}

Output

Model: Unknown, Color: Unknown

2. Parameterized Constructor

A parameterized constructor is a constructor that takes one or more arguments. It is used to provide initial values for the data members of the object.

Syntax

public class ClassName
{
    // Parameterized constructor
    public ClassName(dataType parameter1, dataType parameter2)
    {
        // Initialization code
    }
}

Example

using System;

namespace ConstructorsExample
{
    public class Car
    {
        public string Model { get; set; }
        public string Color { get; set; }

        // Parameterized constructor
        public Car(string model, string color)
        {
            Model = model;
            Color = color;
        }

        public void DisplayInfo()
        {
            Console.WriteLine($"Model: {Model}, Color: {Color}");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Car car = new Car("Toyota", "Red");
            car.DisplayInfo();
        }
    }
}

Output

Model: Toyota, Color: Red

3. Copy Constructor

A copy constructor is a constructor that creates a new object as a copy of an existing object. It takes an object of the same class as a parameter.

Syntax

public class ClassName
{
    // Copy constructor
    public ClassName(ClassName obj)
    {
        // Initialization code
    }
}

Example

using System;

namespace ConstructorsExample
{
    public class Car
    {
        public string Model { get; set; }
        public string Color { get; set; }

        // Parameterized constructor
        public Car(string model, string color)
        {
            Model = model;
            Color = color;
        }

        // Copy constructor
        public Car(Car car)
        {
            Model = car.Model;
            Color = car.Color;
        }

        public void DisplayInfo()
        {
            Console.WriteLine($"Model: {Model}, Color: {Color}");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Car car1 = new Car("Toyota", "Red");
            Car car2 = new Car(car1);

            car1.DisplayInfo();
            car2.DisplayInfo();
        }
    }
}

Output

Model: Toyota, Color: Red
Model: Toyota, Color: Red

4. Static Constructor

A static constructor is used to initialize static data members of a class. It is called automatically before any instance of the class is created or any static members are accessed.

Syntax

public class ClassName
{
    // Static constructor
    static ClassName()
    {
        // Initialization code
    }
}

Example

using System;

namespace ConstructorsExample
{
    public class Car
    {
        public static string Brand { get; set; }
        public string Model { get; set; }
        public string Color { get; set; }

        // Static constructor
        static Car()
        {
            Brand = "Toyota";
        }

        // Parameterized constructor
        public Car(string model, string color)
        {
            Model = model;
            Color = color;
        }

        public void DisplayInfo()
        {
            Console.WriteLine($"Brand: {Brand}, Model: {Model}, Color: {Color}");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Car car1 = new Car("Camry", "Red");
            Car car2 = new Car("Corolla", "Blue");

            car1.DisplayInfo();
            car2.DisplayInfo();
        }
    }
}

Output

Brand: Toyota, Model: Camry, Color: Red
Brand: Toyota, Model: Corolla, Color: Blue

5. Private Constructor

A private constructor is used to restrict the instantiation of a class. It is typically used in classes that contain static members only.

Syntax

public class ClassName
{
    // Private constructor
    private ClassName()
    {
        // Initialization code
    }
}

Example

using System;

namespace ConstructorsExample
{
    public class Logger
    {
        private static Logger instance;

        // Private constructor
        private Logger()
        {
        }

        public static Logger Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new Logger();
                }
                return instance;
            }
        }

        public void Log(string message)
        {
            Console.WriteLine("Log: " + message);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Logger logger1 = Logger.Instance;
            Logger logger2 = Logger.Instance;

            logger1.Log("Logger instance 1");
            logger2.Log("Logger instance 2");

            Console.WriteLine("Same instance: " + (logger1 == logger2));
        }
    }
}

Output

Log: Logger instance 1
Log: Logger instance 2
Same instance: True

Conclusion

Constructors in C# are essential for initializing objects and setting up initial states. Understanding different types of constructors?default, parameterized, copy, static, and private?helps in designing classes that are flexible, reusable, and maintainable. Each constructor type serves specific purposes and can be used to control object creation and initialization effectively.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top