Primary constructors are a newer feature in C# designed to simplify class and record declarations by allowing constructor parameters to be declared inline with the class declaration. This feature makes the syntax more concise and expressive, especially for immutable types.
This document explains what primary constructors are, their syntax, advantages, limitations, and real-world usage examples in C#. We will also compare them with traditional constructors to understand when and why to use primary constructors.
Primary constructors let you declare constructor parameters directly in the class declaration parentheses, rather than defining a separate constructor block. This feature is inspired by similar constructs in languages like Kotlin and Scala.
They aim to reduce boilerplate code by allowing parameter declarations and property initializations in one place.
public class Person(string name, int age)
{
public string Name { get; } = name;
public int Age { get; } = age;
}
Here, string name and int age are primary constructor parameters, automatically available inside the class body.
Primary constructors were proposed for C# 6 and 7 but were postponed multiple times due to design considerations and complexity.
As of C# 12 (May 2025), primary constructors are officially part of the language, primarily supported on classes and structs to simplify initialization patterns.
This marks a significant evolution in C#'s constructor syntax, aiming to reduce ceremony and increase clarity.
A class or struct declaration can have parameters enclosed in parentheses immediately following the name, which represent the primary constructor's parameters.
public class ClassName(Type param1, Type param2, ...)
{
// class body can use param1, param2 directly
}
You can initialize properties inline using primary constructor parameters:
public class Product(string name, decimal price)
{
public string Name { get; } = name;
public decimal Price { get; } = price;
}
Primary constructor parameters are readonly and accessible throughout the class body, including methods and properties:
public class Rectangle(int width, int height)
{
public int Width { get; } = width;
public int Height { get; } = height;
public int Area() => width * height;
}
| Feature | Primary Constructor | Traditional Constructor |
|---|---|---|
| Syntax | Parameters declared inline with class | Constructor method declared inside class |
| Boilerplate | Reduced boilerplate | More verbose, requires explicit constructor method |
| Parameter accessibility | Parameters accessible throughout class | Parameters accessible only inside constructor body |
| Multiple constructors | Only one primary constructor | Supports constructor overloading |
| Initialization | Properties can be initialized inline | Properties initialized inside constructor |
Records in C# (introduced in C# 9) inherently have a concise syntax for primary constructors and immutable data:
public record Person(string Name, int Age);
This single line creates an immutable record with two properties, a primary constructor, equality checks, and other features.
While records make primary constructors and properties even more succinct, classes allow more control and additional members.
public class Employee(int id, string name, string department)
{
public int Id { get; } = id;
public string Name { get; } = name;
public string Department { get; } = department;
public void Display() =>
Console.WriteLine($"{Id}: {Name} works in {Department}");
}
public struct Point(double x, double y)
{
public double X { get; } = x;
public double Y { get; } = y;
public double DistanceFromOrigin() =>
Math.Sqrt(X * X + Y * Y);
}
public class Circle(double radius)
{
public double Radius { get; } = radius;
public double Circumference() => 2 * Math.PI * radius;
}
Primary constructors support inheritance, allowing derived classes to invoke base class primary constructors using base(...).
public class Animal(string name)
{
public string Name { get; } = name;
}
public class Dog(string name, string breed) : Animal(name)
{
public string Breed { get; } = breed;
}
As of now, primary constructor parameters cannot have default values directly, but you can simulate this with overloaded constructors or optional parameters in traditional constructors.
Primary constructor parameters can be used to initialize auto-properties, readonly fields, or backing fields in any way.
Yes, if you declare parameters inline with the class name, you must provide values when creating instances.
Yes, you can define explicit constructors alongside primary constructors, but overloading the primary constructor parameters is not possible.
No. They provide an additional, more concise option but traditional constructors remain valid and sometimes necessary.
Currently, primary constructors do not have explicit access modifiers. The class accessibility applies to the constructor.
Primary constructors in C# simplify object initialization by integrating constructor parameters directly into class and struct declarations. This approach reduces boilerplate, improves readability, and encourages immutable patterns.
While still evolving and with some limitations, primary constructors represent a modern feature of C# aligned with trends in contemporary programming languages.
Understanding how to effectively use primary constructors, alongside traditional constructors, is key to writing clean, expressive, and maintainable C# code.
C# is primarily used on the Windows .NET framework, although it can be applied to an open source platform. This highly versatile programming language is an object-oriented programming language (OOP) and comparably new to the game, yet a reliable crowd pleaser.
The C# language is also easy to learn because by learning a small subset of the language you can immediately start to write useful code. More advanced features can be learnt as you become more proficient, but you are not forced to learn them to get up and running. C# is very good at encapsulating complexity.
The decision to opt for C# or Node. js largely hinges on the specific requirements of your project. If you're developing a CPU-intensive, enterprise-level application where stability and comprehensive tooling are crucial, C# might be your best bet.
C# is part of .NET, a free and open source development platform for building apps that run on Windows, macOS, Linux, iOS, and Android. There's an active community answering questions, producing samples, writing tutorials, authoring books, and more.
Copyrights © 2024 letsupdateskills All rights reserved