1. 🔴 What is a constructor, and what are the different types of constructors in C#?
A constructor is a special member of a class that initializes an object when it is created.
Key points:
-
Constructor name must match the class name.
-
It does not have a return type, not even
void. -
It executes automatically when an object is created using
new. -
Constructors can be overloaded.
-
Constructors cannot be inherited or overridden.
Types of constructors
|
Type |
Purpose |
|---|---|
|
Default constructor |
Initializes an object without arguments |
|
Parameterized constructor |
Initializes an object using supplied values |
|
Copy constructor |
Creates an object using another object's values |
|
Static constructor |
Initializes static members |
|
Private constructor |
Restricts object creation from outside the class |
Example
class Employee
{
public string Name;
// Parameterless constructor
public Employee()
{
Name = "Unknown";
}
// Parameterized constructor
public Employee(string name)
{
Name = name;
}
// Copy constructor
public Employee(Employee emp)
{
Name = emp.Name;
}
}
Usage:
Employee e1 = new Employee();
Employee e2 = new Employee("John");
Employee e3 = new Employee(e2);
Console.WriteLine(e1.Name); // Unknown
Console.WriteLine(e2.Name); // John
Console.WriteLine(e3.Name); // John
Interview key point: Constructors initialize object state. C# automatically supplies a public parameterless constructor for a class only when no instance constructor is explicitly declared.
2. 🔴 What is the difference between a default constructor and a parameterized constructor?
A default constructor is a parameterless constructor supplied automatically by the compiler when a class declares no instance constructors.
A parameterized constructor accepts arguments to initialize an object with specific values.
Example
class Employee
{
public string Name;
public int Age;
public Employee()
{
Name = "Unknown";
Age = 0;
}
public Employee(string name, int age)
{
Name = name;
Age = age;
}
}
Usage:
Employee e1 = new Employee();
Employee e2 = new Employee("John", 30);
|
Default / parameterless |
Parameterized |
|---|---|
|
Accepts no arguments |
Accepts arguments |
|
Can initialize predefined values |
Initializes supplied values |
|
Compiler may generate one automatically |
Must be explicitly defined |
|
Called using |
Called using |
Important: In this example, Employee() is an explicitly written parameterless constructor, not a compiler-generated default constructor.
3. 🔴 What is constructor overloading and constructor chaining?
Constructor overloading
Constructor overloading means defining multiple constructors in the same class with different parameter signatures.
Constructor chaining
Constructor chaining means calling one constructor from another constructor using this() or base().
Example:
class Employee
{
public string Name;
public int Age;
public Employee() : this("Unknown", 0)
{
Console.WriteLine("Default Constructor");
}
public Employee(string name) : this(name, 25)
{
Console.WriteLine("One Parameter Constructor");
}
public Employee(string name, int age)
{
Name = name;
Age = age;
Console.WriteLine("Two Parameter Constructor");
}
}
Usage:
Employee emp = new Employee("John");
Output:
Two Parameter Constructor
One Parameter Constructor
Execution flow:
new Employee("John")
|
v
Employee(string name)
|
| this(name, 25)
v
Employee(string name, int age)
|
v
Initialize Name and Age
|
v
Return to Employee(string name)
Key points:
-
this()calls another constructor in the same class. -
base()calls a constructor in the base class. -
Constructor chaining reduces duplicate initialization logic.
-
Only one constructor initializer (
thisorbase) can be specified for a constructor.
4. 🔴 What is the difference between this and base keywords?
The this keyword refers to the current object, whereas base is used to access members of the base class.
Example
class Employee
{
public string Name;
public Employee(string name)
{
Name = name;
}
public virtual void Display()
{
Console.WriteLine("Employee: " + Name);
}
}
class Manager : Employee
{
public Manager(string name) : base(name)
{
}
public override void Display()
{
base.Display();
Console.WriteLine("Manager: " + this.Name);
}
}
Usage:
Manager manager = new Manager("John");
manager.Display();
Output:
Employee: John
Manager: John
Comparison
|
|
|
|---|---|
|
Refers to current object |
Accesses base class members |
|
Accesses current object's members |
Accesses inherited base members |
|
|
|
|
Can resolve parameter/member name conflicts |
Can invoke base implementation of overridden method |
Key point: Use this for current-object access and constructor chaining; use base to access base-class functionality.
5. 🔴 What is a static class, and how does it differ from a normal class?
A static class is a class that cannot be instantiated and contains only static members (apart from constants and nested types).
It is commonly used for utility methods and helper functionality.
Example
static class Calculator
{
public static int Add(int a, int b)
{
return a + b;
}
}
Usage:
int result = Calculator.Add(10, 20);
Console.WriteLine(result); // 30
Invalid:
Calculator calc = new Calculator(); // Error
Comparison
|
Static class |
Normal class |
|---|---|
|
Cannot create objects |
Can create objects |
|
Contains static members |
Can contain static and instance members |
|
Cannot be inherited |
Can support inheritance |
|
Cannot inherit from a custom class |
Can inherit from another class |
|
Cannot declare instance constructors |
Supports instance constructors |
|
Cannot implement interfaces |
Can implement interfaces |
Real-world examples:
-
Math -
Console -
Convert -
Custom utility classes
Key point: Static classes are suitable for stateless helper functionality. Avoid using mutable static fields for shared application state without considering thread safety.
6. 🔴 What is the difference between static and instance members?
Static members belong to the class, whereas instance members belong to individual objects.
Example
class Employee
{
public static string Company = "ABC Ltd";
public string Name;
public void Display()
{
Console.WriteLine(Name + " - " + Company);
}
}
Usage:
Employee e1 = new Employee();
e1.Name = "John";
Employee e2 = new Employee();
e2.Name = "David";
Employee.Company = "XYZ Ltd";
e1.Display(); // John - XYZ Ltd
e2.Display(); // David - XYZ Ltd
Explanation:
-
Companyis shared by all instances. -
Nameis separate for each object. -
Changing
Employee.Companyaffects the value seen by both objects.
|
Static member |
Instance member |
|---|---|
|
Belongs to class |
Belongs to object |
|
Shared across instances |
Separate per instance |
|
Accessed using class name |
Accessed using object reference |
|
Does not require object creation |
Normally requires an object |
|
Cannot directly access instance members |
Can access static and instance members |
Key point: Static fields have one shared value per constructed generic type, while instance fields maintain individual object state.
7. 🟡 What is a static constructor, and when is it executed?
A static constructor initializes static members of a class.
It is executed automatically once per type, before its first required use, according to the runtime's type-initialization rules.
Example
class DatabaseConfig
{
public static string ConnectionString;
static DatabaseConfig()
{
ConnectionString = "Server=localhost;";
Console.WriteLine("Static Constructor");
}
public static void Display()
{
Console.WriteLine(ConnectionString);
}
}
Usage:
DatabaseConfig.Display();
DatabaseConfig.Display();
Output:
Static Constructor
Server=localhost;
Server=localhost;
Important rules
-
Static constructors cannot have parameters.
-
They cannot have access modifiers.
-
They cannot be called explicitly.
-
Only one static constructor is allowed per class.
-
They execute once per type initialization.
-
They are useful for one-time static initialization.
Interview key point: A static constructor runs automatically before the first instance is created or a static member is accessed, with exact timing governed by .NET type-initialization rules.
8. 🟡 What is the difference between a constructor and a finalizer?
A constructor initializes an object, whereas a finalizer provides a last-chance cleanup mechanism before the garbage collector reclaims an eligible object.
Example
class Employee
{
public Employee()
{
Console.WriteLine("Constructor Executed");
}
~Employee()
{
Console.WriteLine("Finalizer Executed");
}
}
Usage:
Employee emp = new Employee();
Output immediately:
Constructor Executed
The finalizer output is not guaranteed to appear immediately or even before the process terminates.
Comparison
|
Constructor |
Finalizer |
|---|---|
|
Initializes object |
Performs final cleanup |
|
Executes during object creation |
Runs when scheduled by GC |
|
Can accept parameters |
Cannot accept parameters |
|
Can be overloaded |
Cannot be overloaded |
|
Can have access modifiers |
Cannot have access modifiers |
|
Execution is deterministic during creation |
Execution timing is nondeterministic |
Key point: Finalizers should generally be avoided unless a class directly owns unmanaged resources requiring finalization.
9. 🟡 What is the difference between IDisposable, Dispose(), and a finalizer?
These concepts are related to resource management in .NET.
-
IDisposable– An interface defining the cleanup contract. -
Dispose()– A method used to release resources deterministically. -
Finalizer – A cleanup mechanism invoked nondeterministically by the garbage collector.
Example using IDisposable
class FileManager : IDisposable
{
private FileStream? _stream;
public FileManager(string path)
{
_stream = new FileStream(
path, FileMode.OpenOrCreate);
}
public void Dispose()
{
_stream?.Dispose();
_stream = null;
}
}
Usage:
using (FileManager file = new FileManager("test.txt"))
{
Console.WriteLine("File opened");
}
// Dispose() automatically called
Comparison
|
|
|
Finalizer |
|---|---|---|
|
Interface |
Method |
Special cleanup member |
|
Defines cleanup contract |
Executes cleanup logic |
Final cleanup mechanism |
|
Implemented by a class |
Called explicitly or via |
Invoked by GC |
|
Does not perform cleanup itself |
Deterministic cleanup |
Nondeterministic cleanup |
Real-world ASP.NET Core example
using var connection = new SqlConnection(connectionString);
connection.Open();
// Execute database operations
When execution leaves the scope, Dispose() is called automatically, including when an exception occurs.
Important points:
-
The garbage collector manages managed memory, not timely release of external resources.
-
Use
IDisposablefor objects that own disposable resources. -
Prefer
usingorusing varfor automatic cleanup. -
Use
IAsyncDisposableandawait usingwhen asynchronous cleanup is supported and appropriate.
Key point: Prefer deterministic cleanup with Dispose(). Do not rely on finalizers for database connections, files, or network resources.
10. 🟡 Can constructors be private, protected, or static?
Yes. C# supports constructors with different access modifiers, as well as static constructors.
Private constructor
Prevents object creation from outside the class.
class Utility
{
private Utility()
{
}
public static void Show()
{
Console.WriteLine("Hello");
}
}
Utility.Show();
// new Utility(); // Error
Use case: Restrict object creation, such as in a singleton implementation or factory-controlled class.
Protected constructor
Allows derived classes to call the constructor.
class Employee
{
protected Employee()
{
Console.WriteLine("Employee Constructor");
}
}
class Manager : Employee
{
public Manager()
{
Console.WriteLine("Manager Constructor");
}
}
Use case: Base classes intended for inheritance.
Static constructor
Initializes static members automatically.
class Settings
{
public static string AppName;
static Settings()
{
AppName = "My Application";
}
}
Comparison
|
Constructor |
Purpose |
|---|---|
|
|
Object creation from accessible external code |
|
|
Object creation restricted to the containing type |
|
|
Accessible to derived classes |
|
|
Accessible within the same assembly |
|
|
One-time type initialization |
Key point: Static constructors cannot have explicit access modifiers or parameters.
11. 🟢 What is object initialization, and how do object initializers work?
Object initialization means assigning initial values to an object's fields or properties.
C# supports object initializers, which allow values to be assigned during object creation without explicitly calling setter methods afterward.
Traditional approach
class Employee
{
public string Name { get; set; } = "";
public int Age { get; set; }
}
Employee emp = new Employee();
emp.Name = "John";
emp.Age = 30;
Object initializer approach
Employee emp = new Employee
{
Name = "John",
Age = 30
};
Both approaches initialize the same object properties.
Constructor vs object initializer
Constructor:
class Employee
{
public string Name { get; set; }
public Employee(string name)
{
Name = name;
}
}
Employee emp = new Employee("John");
Object initializer:
Employee emp = new Employee
{
Name = "John"
};
The initializer example requires an accessible parameterless constructor.
Important points
-
Object initializers reduce repetitive assignment code.
-
They work with accessible writable fields and properties.
-
The constructor executes before initializer assignments.
-
They can also initialize
initproperties. -
requiredmembers can enforce mandatory initialization.
Key point: Use constructors for essential initialization logic and object initializers for readable property assignments.
Quick Interview Revision
|
Concept |
Key point |
|---|---|
|
Constructor |
Initializes an object |
|
Default constructor |
Compiler-generated parameterless constructor |
|
Parameterized constructor |
Accepts initialization values |
|
Constructor overloading |
Multiple constructors with different parameters |
|
Constructor chaining |
|
|
|
Current object |
|
|
Base class functionality |
|
Static class |
Cannot be instantiated |
|
Static member |
Shared at type level |
|
Instance member |
Belongs to individual object |
|
Static constructor |
Executes once during type initialization |
|
Finalizer |
Nondeterministic GC cleanup |
|
|
Defines cleanup contract |
|
|
Releases resources deterministically |
|
|
Automatically invokes |
|
Private constructor |
Restricts object creation |
|
Protected constructor |
Supports derived-class construction |
|
Object initializer |
Initializes fields/properties during creation |
Interview priority: For Senior .NET Developer and Technical Lead interviews, focus especially on constructor chaining (this vs base), static vs instance members, static constructor execution, IDisposable vs finalizers, and the using statement. These are frequently relevant to real-world ASP.NET Core development and resource management.