top of page

C# tips and tricks – part 4

Primary Constructors in C#

C# is continuously evolving to offer more convenient ways to write clean and readable code. One of the upcoming features planned for future versions is the primary constructor, which aims to simplify object initialization by allowing class members to be initialized directly within the class definition itself.


What are Primary Constructors?

A primary constructor is a form of constructor that is defined at the class level, instead of being defined inside the class body like traditional constructors. This results in a more concise and clear syntax.

Example:
public class Employee(string name, int age)
{
    public string Name { get; } = name;
    public int Age { get; } = age;
}

 

In this example, the Employee class uses a primary constructor. Instead of defining a constructor within the class body, the constructor parameters are defined directly in the class definition, and the members Name and Age are initialized when the object is created.

 

How would this class look the old way?

Without using the primary constructor, the traditional approach would look like this:

public class Employee
{
    public string Name { get; }
    public int Age { get; }
 
    public Employee(string name, int age)
    {
        Name = name;
        Age = age;
    }
}

 

Here, we create a constructor inside the class body that accepts name and age parameters and assigns them to the class members Name and Age.

 

Benefits of Primary Constructors:

  1. Shorter code: There's no need to write additional code for constructors and member initialization.

  2. Clarity and readability: Defining the primary constructor at the class header makes the code easier to understand.

  3. Reduced errors: Initialization is more intuitive and less prone to mistakes.


Limitations and potential drawbacks:

  • Primary constructors are best suited for simpler classes. For more complex classes with many dependencies or logic, traditional constructors might be more appropriate.

  • The feature is still in development and is not available in all versions of C#.






Amexis Team

コメント


bottom of page