Constructors in C#
Constructors in C# – Types, Use Cases, Pros, and Cons
Constructors are special methods used to initialize objects in C#. They play a crucial role in object creation and setup.
- Initializing object properties or fields
- Setting default values
- Performing setup logic (e.g., dependency injection)
1. Default Constructor
public class User {
public string Name;
public User() {
Name = "Guest";
}
}
Use Case: For default object creation without custom input.
- ✅ Simple and compiler-generated
- ❌ Limited customization
2. Static Constructor
public class Logger {
static Logger() {
// One-time config
}
}
- ✅ Ensures static setup
- ❌ Cannot take parameters, hard to test
3. Primary Constructor (C# 12+)
public class Product(string name, decimal price) {
public string Name { get; } = name;
public decimal Price { get; } = price;
}
- ✅ Minimal syntax
- ❌ Requires C# 12
4. Private Constructor
public class AppConfig {
private AppConfig() { }
public static AppConfig Instance { get; } = new AppConfig();
}
- ✅ Singleton & control instantiation
- ❌ No external usage
5. Overloaded Constructors
public class Car {
public string Model;
public Car() {
Model = "Unknown";
}
public Car(string model) {
Model = model;
}
}
- ✅ Flexible creation
- ❌ Can become confusing
6. Chained Constructors
public class Student {
public string Name;
public int Age;
public Student(string name) : this(name, 18) {}
public Student(string name, int age) {
Name = name;
Age = age;
}
}
- ✅ Avoids redundancy
- ❌ Slightly complex to debug
7. Base Constructor
public class Animal {
public Animal(string name) {}
}
public class Dog : Animal {
public Dog() : base("Dog") {}
}
- ✅ Inheritance-friendly
- ❌ Coupled to base constructor
8. Constructor with Optional Parameters
public class Employee {
public string Name;
public string Department;
public Employee(string name = "John", string department = "HR") {
Name = name;
Department = department;
}
}
- ✅ Cleaner, fewer overloads
- ❌ May hide logic with defaults
9. Copy Constructor
public class User {
public string Name;
public User(User other) {
Name = other.Name;
}
}
- ✅ Good for cloning
- ❌ Manual work, shallow copies risky
10. Constructor Injection (DI)
public class OrderService {
private readonly ILogger _logger;
public OrderService(ILogger logger) {
_logger = logger;
}
}
- ✅ Testable, loosely coupled
- ❌ May grow in size with more dependencies
Summary Table
| Constructor Type | Use Case | Pros | Cons |
|---|---|---|---|
| Default | Basic object setup | Simple, auto-generated | No custom logic |
| Static | One-time setup | Runs once | No params |
| Primary | Immutable types | Concise | Needs C# 12+ |
| Private | Singletons | Prevents new instances | No external access |
| Overloaded | Flexible setup | User-friendly | Can be confusing |
| Chained | Shared logic | No duplication | Complex to debug |
| Base | Inheritance | Parent setup | Tightly coupled |
| Optional Params | Defaults | Cleaner | Hidden logic |
| Copy | Clone objects | Manual copy | Shallow risks |
| DI | Inject services | Testable | Constructor bloat |
Final Thoughts
Choosing the right constructor type improves clarity, flexibility, and maintainability in your C# applications. Understand each type’s trade-offs and apply them where appropriate for clean, robust object-oriented designs.
Comments
Post a Comment