π¦ Object Initializers = Clean Creation
Constructors with many params are messy. Object initializers create objects cleanly. Readable, concise, flexible.
β Constructor
public class User
{
public string Name { get; set; }
public int Age { get; set; }
public string Email { get; set; }
public User(string name, int age, string email)
{
Name = name;
Age = age;
Email = email;
}
}
var user = new User("Alice", 30, "alice@example.com");
β Object Initializer
public class User
{
public string Name { get; set; }
public int Age { get; set; }
public string Email { get; set; }
}
var user = new User
{
Name = "Alice",
Age = 30,
Email = "alice@example.com"
};
π― Object Initializer Examples
// Simple
var user = new User { Name = "Alice", Age = 30 };
// Nested
var order = new Order
{
Id = 1,
Customer = new Customer { Name = "Alice" },
Items = new List-
{
new Item { Product = "Laptop", Price = 999 },
new Item { Product = "Mouse", Price = 25 }
}
};
// With collections
var users = new List
{
new User { Name = "Alice", Age = 30 },
new User { Name = "Bob", Age = 25 },
new User { Name = "Charlie", Age = 35 }
};
// With dictionary
var config = new Dictionary
{
["api_key"] = "abc123",
["endpoint"] = "https://api.example.com"
};
// With init-only properties
public class Settings
{
public string ApiKey { get; init; }
public int Timeout { get; init; }
}
var settings = new Settings { ApiKey = "key", Timeout = 30 };
// Object Initializer Benefits
- No constructor required
- Readable (property names visible)
- Flexible (set only needed properties)
- Works with init-only setters
- Works with anonymous types
π‘ Object Initializer Tips
- No constructor required
- Readable (property names visible)
- Flexible (set only needed properties)
- Works with init-only setters
- Works with anonymous types
“Object initializers are clean. No constructor boilerplate. Essential for modern C#.”
