What is a constructor in C#?
Answer
A constructor is a special method called when an object is created, used to initialize the object's state. It has the same name as the class and no return type. Default constructor: takes no parameters — auto-generated by the compiler if no constructor is defined. Parameterized constructor: public Person(string name, int age) { Name = name; Age = age; }. Constructor chaining: this(...) calls another constructor in the same class; base(...) calls the parent class constructor. Static constructor: static ClassName() { } — called once, before the first use of the class, for static initialization (setting static fields, loading resources). Primary constructors (C# 12): class Person(string name, int age) — concise syntax, parameters scoped to the whole class body. Object initializers (new Person { Name = "Alice" }) are different — they call the constructor then set properties.
Previous
What is a property in C# and how does it differ from a field?
Next
What is a delegate in C#?