NashTech Blog

A Closer Look at What’s New in .NET 8 Series (Part 1) – C# 12

Table of Contents
digitization, transformation, hand-4667376.jpg

C# 12 includes the following new features that I find useful in our daily jobs:

  • Primary Constructors
  • Collection Expressions

Primary Constructor

I’m excited to share that you can now create primary constructors in any class and struct. Previously, primary constructors were limited to record types, but this restriction has been lifted. The parameters of primary constructors are now accessible throughout the entire body of the class.

It’s important to highlight that the compiler will generate public properties for primary constructor parameters only in record types, which include both record classes and record structs. For non-record classes and structs, this automatic behavior is not applied, allowing for greater flexibility depending on your specific requirements.

Collection Expression

Collection Expression offer a concise syntax for creating common collection values. You can now inline other collections into these values using the spread operator (...).

This feature allows you to create several collection-like types without needing additional support from the Base Class Library (BCL). These types include:

  • Array types, such as int[].
  • System.Span<T> and System.ReadOnlySpan<T>.
  • Types that support collection initializers, such as System.Collections.Generic.List<T>

The following examples show uses of same collection expressions to create several collection-like types:

The spread operator (..) in collection expressions replaces its argument with the elements from that collection, making it a powerful tool for constructing collections efficiently. The argument must be a collection type. Here are some examples to illustrate how the spread operator works:

Picture of toanleh

toanleh

Leave a Comment

Your email address will not be published. Required fields are marked *

Suggested Article

Scroll to Top