What are constructors and their types in C#?

Beginner

Answer

Constructors are special methods called when an object is created. They initialize the object's state.
Types:

  • Default Constructor: No parameters, provided by compiler if none defined
  • Parameterized Constructor: Takes parameters for initialization
  • Copy Constructor: Not directly supported, must be implemented manually
  • Static Constructor: Initializes static members, called once per type
  • Private Constructor: Prevents instantiation (often used in singleton pattern)
public class Person
{
    // Parameterized constructor
    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
    // Static constructor
    static Person()
    {
        // Initialize static members
    }
}