Advertisement
Advanced C#, Fundamentals

How do C# 12's primary constructors on regular classes (not just records) change how you write simple constructor-and-field boilerplate?

Short answer

Primary constructors let you declare constructor parameters directly in the class declaration's header, making those parameters available throughout the ENTIRE class body (not just the constructor) without manually declaring separate fields and an explicit constructor body to…

Save C# mock interview
Advertisement
AModel answer
Primary constructors let you declare constructor parameters directly in the class declaration's header, making those parameters available throughout the ENTIRE class body (not just the constructor) without manually declaring separate fields and an explicit constructor body to assign them — though unlike records, primary constructor parameters on a regular class aren't automatically exposed as public properties.
public class Point(int x, int y) { // primary constructor, C# 12
  public double DistanceFromOrigin() => Math.Sqrt(x * x + y * y); // 'x' and 'y' usable directly, no field needed
}
Real-world example
Reducing constructor-and-field boilerplate for simple classes that just need to store and use a few constructor-provided values internally.
Likely follow-ups
  • Why don't primary constructor parameters on a plain class automatically become public properties, unlike with records?
Related topics