---
title: "Less boilerplate code with the new primary constructor in C# 12"
description: "The new language feature *\"primary constructor\"* which will be released with C# 12 / .NET 8 this year (November 2023) allows you to remove some ceremonial code. Let's see how."
updated: 2023-09-24
tags: ["C#", ".NET", ".NET 8", "C# 12"]
canonical: "https://steven-giesel.com/blogPost/1b2a4f18-86da-42d3-9ddc-8b41ed1eba0f/less-boilerplate-code-with-the-new-primary-constructor-in-c-12"
---

# Less boilerplate code with the new primary constructor in C# 12

The new language feature *"primary constructor"* which will be released with C# 12 / .NET 8 this year (November 2023) allows you to remove some ceremonial code. Let's see how. [If you need a refresher on the **primary constructors** just click check out my blog post](https://steven-giesel.com/blogPost/a210c97e-fe68-45de-afa1-d053d75f6f7d).

## Dependency Injection setup
Prior to .NET 8 if we have a class that lives inside the Dependency Injection looks roughly like this:
```csharp
public class MyService
{
  private readonly IDepedent dependent;
  
  public MyService(IDependent dependent)
  {
    this.dependent = dependent;
  }
  
  public void Do() 
  {
    dependent.DoWork();
  }
}
```

Thre more services you have, the more "setup" code you need. Here this new feature can help, and remove the whole `private readonly` part as well as all the initialization:
```csharp
public class MyService(IDependent dependent)
{
  public void Do() 
  {
    dependent.DoWork();
  }
}
```

These two classes are completely the same. The compiler takes care of all the boilerplate code for you and creates the fields and assignments. You can have a look on [sharplab.io](https://sharplab.io/#v2:EYLgtghglgdgPgAQMwAJYBcCmAnAZhAY0xQEkARTAB0xgBMb0BYAKAG8WVOUEAWFMgPYB1AdgDWACgCUAbhYBfFi2TcATCgCyATwDKOAG5QiE8lRr0Y6FPWp0GUlu2acVvfgOkoOKJ12tm7SwA6QRFxaTlnFEVmeSA==) to see that behind the scenes, roughly the same code is generated.

The **downside** to this approach is more that we have yet another way of doing a thing. That might be especially overwhelming for new joiners to the language that discover both approaches in one code base. A more extreme version of that is how you can check for `null` references - there are at least 4 ways to do so.