C# Interview Question #21

What is a constructor in C#?

Classes, Constructors & Properties Junior Beginner

Quick Interview Answer

A constructor is a special member of a class that runs automatically when an object is created. It has the same name as the class and has no return type.

Detailed Explanation

A constructor is a special member of a class that runs automatically when an object is created. It has the same name as the class and has no return type.

Constructors are mainly used to initialize an object's required state and dependencies. They can be parameterless or accept parameters, and a class can have multiple overloaded constructors.

Code Example

public class Product
{
    public string Name { get; set; }

    public Product(string name)
    {
        Name = name;
    }
}

var product = new Product("Laptop");