Primary constructors allow you to declare constructor parameters directly on the class or struct declaration. This is especially useful when your type mainly exists to store and validate incoming values. The parameters are in scope for field/property initialization, helping you avoid repeating assignments. Think of it as a cleaner “front door” for creating objects, while keeping the type’s purpose obvious.
Try It Yourself
public class Customer(int id, string name)
{
public int Id { get; } = id > 0 ? id : throw new ArgumentOutOfRangeException(nameof(id));
public string Name { get; } = !string.IsNullOrWhiteSpace(name) ? name : throw new ArgumentException("Name required");
public override string ToString() => $"{Id} - {Name}";
}
// Usage:
var c = new Customer(101, "Asha");
Console.WriteLine(c);
Real-world use case: DTO-style domain objects in microservices where you want quick validation at construction time.