C# 12: The Features That Are Turning Heads

CSharp Features, .NET, Microsoft

Alex Maher

--

C# 12, introduced in the latest Visual Studio previews and .NET 8 preview SDK it’s making waves in the developer community.

C# keeps getting better with each version, and this one’s no exception.

It’s packed with new tools that make our coding life easier and more fun. If you’re a C# fan like me, you’re going to love exploring all the new stuff.

Let’s jump in and see what it’s all about!

Primary Constructors

Primary constructors are a game-changer for object initialization. Instead of declaring properties and then a constructor separately, developers can now do both simultaneously.

public class Person(string name, int age)
{
public string Name { get; } = name;
public int Age { get; } = age;
}

This feature shines especially for classes intended to be immutable. It reduces boilerplate code, making the codebase cleaner and more readable. For developers, this means faster coding with fewer errors.

Optional Parameters in Lambda Expressions

Lambda expressions have always been a powerful tool in C#. With the introduction of optional parameters, their versatility has been enhanced.

Func<int, int, int> add = (x, y = 5) => x + y;
Console.WriteLine(add(10)); // Outputs 15

This feature reduces the need for multiple overloads, leading to cleaner and more maintainable code. It’s especially useful when working with delegates or events, providing flexibility in function signatures.

Alias Any Type

The expanded capabilities of the using alias directive in C# 12 bring a new level of flexibility and clarity to the code. By allowing developers to create semantic aliases for more complex types, the code becomes more readable and maintainable.

Here’s an example:

// This would not compile in versions before C# 12
using Person = (string Name, int Age);
using Matrix = double[,];

In essence, the ability to alias any type in C# 12 is not just a syntactic sugar but…

--

--

Alex Maher

.NET C# dev with 10+ yrs exp, self-taught & passionate web developer. Sharing tips & experiences in C# and web dev.