Your browser may have trouble rendering this page. See supported browsers for more information.

Contents

274 Articles
13 Comments

Search

Two Days Ago

Avoid primary constructors in C# (for now)

Published by marco on

tl;dr: avoid C# 12's primary constructors for classes except for very small, simple classes, in which case you should consider using a record instead.

The following video discusses the downsides of the current implementation of primary constructors:

The C# 12 Feature You Shouldn’t Use, Yet by Nick Chapsas (YouTube)

To sum up:

  • Primary constructors don’t have a readonly backing field; you can still assign to it within the type.
  • You can’t control the visibility of the generated property or backing field.
  • You can’t throw exceptions, except in a... [More]