Bars Icon

What’s New in C# 12: Primary Constructors, Collection Expressions, and More

28-12-2023 11:16 AM

As part of the .NET 8 launch, on November 14th Microsoft unveiled the new features of C# 12, the latest version of the popular .NET programming language. As announced the most notable improvements include collection expressions, primary constructors for all classes and structs, syntax to alias any type, and default parameters for lambda expressions.
C# 12 introduces the extension of primary constructors to include this feature in all classes and structs, not limited to records only. This enhancement allows the definition of constructor parameters directly within the class declaration.
The primary constructor parameters find versatile applications, serving as arguments for base() constructor invocations, encouraging member field or property initialisation, referencing within instance members, and facilitating dependency injection by eliminating boilerplate code.\

The primary constructor parameter operates as a class-wide scoped parameter, applicable to various types, including class, struct, record class, and record struct. Notably, when applied to record types, the compiler automatically generates public properties for each primary constructor parameter, simplifying member management for record structures.
Collection expressions are also introduced, which simplifies the syntax for creating various collections, providing a unified approach. As stated, this eliminates the need for distinct syntax when initializing arrays, lists, or spans. The compiler generates efficient code, optimizing collection capacity and avoiding unnecessary data copying.Additionally, a new spread operator simplifies the inclusion of elements from multiple collections. The team stated that this feature is open to feedback for potential future expansions, including dictionaries and support for var (natural types) in upcoming C# versions.Regarding performance in C# 12, two new features ref readonly parameters and inline arrays are introduced to enhance raw memory handling and boost application performance. The ref readonly parameters offer an adaptable approach to passing parameters by reference or value, particularly beneficial when a method needs the memory location of an argument without modification.