C# - Primary constructors

Primary Constructors in C#

Introduction

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.

1. What Are 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.

Example Syntax

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.

2. History and Status of Primary Constructors in C#

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.

3. Syntax and Semantics of Primary Constructors

3.1 Declaration Syntax

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
}

3.2 Using Primary Constructor Parameters

  • Parameters are implicitly declared as readonly fields.
  • You can assign them directly to properties or use them in method bodies.
  • You cannot declare multiple primary constructors β€” only one parameter list allowed.

3.3 Property Initialization

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;
}

3.4 Parameter Usage

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;
}

4. Comparison with Traditional Constructors

FeaturePrimary ConstructorTraditional 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

5. Benefits of Using Primary Constructors

  • Concise syntax: Combine parameter declaration and constructor definition in one place.
  • Less boilerplate: Eliminates need for repetitive constructor code.
  • Readonly access: Parameters are readonly and accessible throughout the class.
  • Clear intent: Constructor parameters are more visible and part of the type signature.
  • Encourages immutability: Makes it easier to create immutable types with readonly properties.

6. Limitations and Considerations

  • Only one primary constructor per class or struct allowed; you cannot overload primary constructors.
  • Complex constructor logic (e.g., validation, branching) requires a separate explicit constructor or factory method.
  • Primary constructor parameters cannot have default values directly (this might evolve with future C# versions).
  • Not supported on all kinds of types (interfaces, delegates, or enums).

7. Using Primary Constructors with Records

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.

Records vs Classes Primary Constructors

While records make primary constructors and properties even more succinct, classes allow more control and additional members.

8. Real-World Examples of Primary Constructors

Example 1: Immutable Class

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}");
}

Example 2: Struct with Primary Constructor

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);
}

Example 3: Using Primary Constructor Parameters in Methods

public class Circle(double radius)
{
    public double Radius { get; } = radius;

    public double Circumference() => 2 * Math.PI * radius;
}

9. Advanced Topics

9.1 Combining Primary Constructors with Inheritance

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;
}

9.2 Using Primary Constructors with Default Values

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.

9.3 Combining with Property Initializers

Primary constructor parameters can be used to initialize auto-properties, readonly fields, or backing fields in any way.

10. FAQ About Primary Constructors

Q1: Are primary constructors mandatory if declared?

Yes, if you declare parameters inline with the class name, you must provide values when creating instances.

Q2: Can I have both primary and explicit constructors?

Yes, you can define explicit constructors alongside primary constructors, but overloading the primary constructor parameters is not possible.

Q3: Do primary constructors replace traditional constructors?

No. They provide an additional, more concise option but traditional constructors remain valid and sometimes necessary.

Q4: Can primary constructors be private or protected?

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.

logo

C#

Beginner 5 Hours

Primary Constructors in C#

Introduction

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.

1. What Are 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.

Example Syntax

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.

2. History and Status of Primary Constructors in C#

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.

3. Syntax and Semantics of Primary Constructors

3.1 Declaration Syntax

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 }

3.2 Using Primary Constructor Parameters

  • Parameters are implicitly declared as readonly fields.
  • You can assign them directly to properties or use them in method bodies.
  • You cannot declare multiple primary constructors — only one parameter list allowed.

3.3 Property Initialization

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; }

3.4 Parameter Usage

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; }

4. Comparison with Traditional Constructors

FeaturePrimary ConstructorTraditional 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

5. Benefits of Using Primary Constructors

  • Concise syntax: Combine parameter declaration and constructor definition in one place.
  • Less boilerplate: Eliminates need for repetitive constructor code.
  • Readonly access: Parameters are readonly and accessible throughout the class.
  • Clear intent: Constructor parameters are more visible and part of the type signature.
  • Encourages immutability: Makes it easier to create immutable types with readonly properties.

6. Limitations and Considerations

  • Only one primary constructor per class or struct allowed; you cannot overload primary constructors.
  • Complex constructor logic (e.g., validation, branching) requires a separate explicit constructor or factory method.
  • Primary constructor parameters cannot have default values directly (this might evolve with future C# versions).
  • Not supported on all kinds of types (interfaces, delegates, or enums).

7. Using Primary Constructors with Records

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.

Records vs Classes Primary Constructors

While records make primary constructors and properties even more succinct, classes allow more control and additional members.

8. Real-World Examples of Primary Constructors

Example 1: Immutable Class

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}"); }

Example 2: Struct with Primary Constructor

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); }

Example 3: Using Primary Constructor Parameters in Methods

public class Circle(double radius) { public double Radius { get; } = radius; public double Circumference() => 2 * Math.PI * radius; }

9. Advanced Topics

9.1 Combining Primary Constructors with Inheritance

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; }

9.2 Using Primary Constructors with Default Values

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.

9.3 Combining with Property Initializers

Primary constructor parameters can be used to initialize auto-properties, readonly fields, or backing fields in any way.

10. FAQ About Primary Constructors

Q1: Are primary constructors mandatory if declared?

Yes, if you declare parameters inline with the class name, you must provide values when creating instances.

Q2: Can I have both primary and explicit constructors?

Yes, you can define explicit constructors alongside primary constructors, but overloading the primary constructor parameters is not possible.

Q3: Do primary constructors replace traditional constructors?

No. They provide an additional, more concise option but traditional constructors remain valid and sometimes necessary.

Q4: Can primary constructors be private or protected?

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.

Related Tutorials

Frequently Asked Questions for C#

C# is much easier to learn than C++. C# is a simpler, high-level-of-abstraction language, while C++ is a low-level language with a higher learning curve.

C# outshines Python when it comes to runtime performance. As a compiled language, C# code is converted to machine code, which can be executed more efficiently by the processor. This results in faster execution times and better performance, especially in resource-intensive tasks.

Python and JavaScript programmers also earn high salaries, ranking #3 and #4 in compensation. 
C# is the highest-paid programming language but has less demand than Python, JavaScript, and Java.

No. Microsoft has invested substantially in ensuring that C# is the dominant language today, spending two billion dollars on marketing and attempting to convince developers to embrace this new platform, which is also based on the.NET foundation.

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.


You can’t be able to become Master of C# in 3 months since it has many concepts to learn and implement. NOTE: no one can become master in particular programming language. Everyday they introducing new concepts we need to get practice on it which practically somewhat tough.

C-Sharp is one of the most widely used languages for creating system backend.It's because of its incredible features, such as Windows server automation. Apart from that, it's fantastic because it runs codes quite quickly. It can also be used to create CLI applications and game creation.

Easy to learn and use: C# is simpler than Java due to its use of fewer keywords and usually shorter lines of code. Hence, it is easier to learn to code in C# compared to Java. Flexible Data Types: C# provides more flexibility in defining data types than Java.

Four steps of code compilation in C# include : 
  • Source code compilation in managed code.
  • Newly created code is clubbed with assembly code.
  • The Common Language Runtime (CLR) is loaded.
  • Assembly execution is done through CLR.

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.


Among other languages, C# is gaining huge popularity for developing web-based applications. Its core concepts help build an interactive environment and provide functionalities that the dynamic web platform requires. Most aspiring full-stack developers choose this versatile language.

The C# programming language was designed by Anders Hejlsberg from Microsoft in 2000 and was later approved as an international standard by Ecma (ECMA-334) in 2002 and ISO/IEC (ISO/IEC 23270 and 20619) in 2003. Microsoft introduced C# along with .NET Framework and Visual Studio, both of which were closed-source. 

C# outshines Python when it comes to runtime performance. As a compiled language, C# code is converted to machine code, which can be executed more efficiently by the processor. This results in faster execution times and better performance, especially in resource-intensive tasks.

Yes, C# is used by many large organizations, start-ups and beginners alike. It takes some of the useful features of C and adds syntax to save time and effort. Although C# is based on C, you can learn it without any knowledge of C β€” in fact, this course is perfect for those with no coding experience at all!

C# is a very mature language that evolved significantly over the years.
The C# language is one of the top 5 most popular programming languages and .NET is the most loved software development framework in the world.
TIOBE Index predicts C# as 2023 'Language of the Year' close to overtake Java in popularity.

Generally, the C# language is not limited to the Windows operating system. In a sense, however, it is limited to Microsoft software. C# language "belongs" to Microsoft, it is developed by Microsoft and it is Microsoft that provides the runtime environment required for the operation of programs written in C#.

C# (pronounced "C sharp") is called so because the "#" symbol is often referred to as "sharp." The name was chosen by Microsoft when they developed the language. It's a play on words related to musical notation where "C#" represents the musical note C sharp.

Dennis MacAlistair Ritchie (September 9, 1941 – c. October 12, 2011) was an American computer scientist. He created the C programming language and, with long-time colleague Ken Thompson, the Unix operating system and B language.

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.


line

Copyrights © 2024 letsupdateskills All rights reserved