C# 12 was released in November along with .NET 8, introducing new features such as primary constructors, collection expressions, inline arrays, and more, making it easier to write efficient code. In this article, we will explore the key new features in C# 12.
In order to work with the code examples provided in this article, please ensure that Visual Studio 2022 is installed on your system. If not, you can download Visual Studio 2022 here.
Create a Console Application Project
First, let’s create a .NET Core console application project in Visual Studio. Here are the steps to create a new project:
- Launch the Visual Studio IDE.
- Click on “Create new project.”
- In the “Create new project” window, select “Console App (.NET Core).”
- Click Next.
- In the “Configure your new project” window, specify the name and location for the new project.
- Click Next.
- In the “Additional information” window shown next, choose “.NET 8.0 (Long Term Support)” as the framework version.
- Click Create.
We’ll use this .NET 8 console application project to work with the new C# 12 features in the subsequent sections of this article.
Primary Constructors in C# 12
Primary constructors are a new feature in C# 12 that allow you to declare constructors whose parameters are available throughout the body of the type. They enable you to declare constructors inline with the type declaration, making the syntax more precise and concise.
You can now create primary constructors in any struct or class, not just limited to record types. By using primary constructors, you no longer need separate constructor definitions.
Here’s an example of a primary constructor declared inside a struct:
public readonly struct Rectangle(double x, double y) { public readonly double Area { get; } = x * y; }
You would typically use primary constructors to initialize a member or a field of the containing type, as an argument when calling the base() constructor, or to reference a constructor parameter in an instance member of the containing type.
Below is a simple implementation of a primary constructor declared inside a class:
public class Author(int Id, string firstName, string lastName) { public int Id { get; } = Id; public string FirstName { get; } = firstName; public string LastName { get; } = lastName; public override string ToString() => $"Author Id: {Id}, First Name: {FirstName}, Last Name: {LastName}"; }
Note that the ToString() method has been overridden in the Author class, allowing you to create an instance of the Author class by passing parameters to its primary constructor and then call the ToString() method on the instance to display the value of those properties.
Collection Expressions in C# 12
C# 12 introduces collection expressions, which allow you to use a more concise syntax when creating collections such as arrays, lists, and dictionaries.
Here’s an example of using a collection expression to initialize a list of strings:
List daysOfWeek = new() { "Sunday","Monday", "Tuesday","Wednesday", "Thursday", "Friday", "Saturday" };
Inline Arrays in C# 12
C# 12 introduces inline arrays, which are struct-based arrays of fixed size. These arrays can be used to efficiently manage buffers without the need for the unsafe keyword.
Here is how you can declare an inline array in C# 12:
[System.Runtime.CompilerServices.InlineArray(50)] public struct Buffer { private int _element; }
You can now use your inline array much the same way you would use any other array in C#.
Default Lambda Parameters in C# 12
C# 12 allows you to specify default parameter values in lambda expressions, making your lambda expressions more flexible and expressive.
Here’s an example of specifying a default parameter value in a lambda expression in C# 12:
var AddIntegers = (int x, int y = 1) => x + y;
You can then call the lambda expression as shown in the code snippet.
Ref Readonly Parameters in C# 12
Support for ref readonly parameters was initially introduced in C# 7.2. C# 12 builds upon this feature, allowing you to use ref readonly parameters in several other scenarios.
Here’s an example of how we can use ref readonly parameters in C# 12:
void Display(in int x, in int y) { Console.WriteLine($"The value of x is : {x}, the value of y is : {y}"); }
You might want to use ref readonly parameters when you want to pass large objects to methods by reference and avoid the cost of unnecessary method copying while ensuring the immutability of the parameters.
Interceptors in C# 12
C# 12 introduces interceptors, which can help you to reroute method calls without changing the original piece of code. Please note that interceptors are an experimental feature available in preview mode and are not recommended for production use.
TargetFramework .NET 8
Note that you will need to have .NET 8 installed on your computer to work with C# 12. If you want to change your existing projects to use C# 12, you will need to specify the TargetFramework to .NET 8.
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net8.0</TargetFramework> ... </PropertyGroup> </Project>
C# 12 makes working with C# easier than ever. You can learn more about the new features in C# 12 here and here.
Copyright © 2023 IDG Communications, Inc.