C# 14 - New Features
Welcome welcome to the C# 14 new features! Here in this Post, I will show you some examples of the new features that are coming in C# 14.
If you want to stay updated on the latest news for C#, .NET, ASP.NET, Blazor, and more, please follow the official .NET repositories on GitHub.
You can also find all the examples from this post on my GitHub.
How to test the new features
To test the preview features, you need to install the latest version of .NET and enable preview features in your project.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
...
<LangVersion>preview</LangVersion>
...
</PropertyGroup>
The new features in C# 14 aren't exclusive to .NET 10, you can also use them in previous versions.
New features
1. Null-conditional assignment
Before this feature, to assign a value to a property without risking an exception when the object was null, you had to do something like this:
Person? me = null;
if (me is not null)
{
me.Name = "Nelson";
}
Right now, you can do this:
Person? me = null;
me?.Name = "Nelson";
Pros
It is less verbose.
Cons
I'm not sure if it will be a problem, but if developers start using this feature in all assignments, they might postpone possible errors to other parts of the code.
My opinion
I really love this feature. In recent years, the C# team has been working hard to make the language more concise and less verbose, which is fantastic. Less code, less text, and less clutter for our eyes. However, I'm not entirely convinced that, in this particular case, it will make C# more readable. Now we only have a ?
to signal the compiler to check for nullability, whereas before we had an explicit check like if (me is not null)
. That said, I love it and I’ll start using it in my code ❤️.
Example
Person? me = new Person { Name = "Nelson" };
Person? you = null;
Person? he = null;
me?.Name = "Nelson Nobre"; // This will assign because "me" is not null
you?.Name = "John Doe"; // This will not assign because "you" is null, but it won't throw an exception
if (he is not null)
{
he.Name = "Tommy"; // Here the previous approach to prevent throwing an exception
}
Console.WriteLine($"me: {me?.Name}, you: {you?.Name}, he: {he?.Name}"); // Output: me: Nelson Nobre, you: null, he: null
class Person
{
public string? Name { get; set; }
}
I'll continue to update this post with more examples and insights as they become available.