You can now try out some C# 11.0 Preview features if you have the latest RTM version of Visual Studio and .NET SDK (Visual Studio 2022 17.1 and .NET SDK 6.0.200 respectively) installed in your machine. And by the way, Visual Studio 2022 17.2 Preview 1 and .NET 7 Preview 1 are also available if you are interested.
In this post let's have a look at a nice feature that's available with C# 11.0, which is improved Parameter Null Checking.
First, make sure you have set <LangVersion> to preview in your .csproj file.
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net6.0</TargetFramework> <ImplicitUsings>enable</ImplicitUsings> <LangVersion>preview</LangVersion> </PropertyGroup> </Project>
Consider the below code where you are doing a null check of parameters inside a method.
Prior to C# 10,
static void PrintFullName(Person person) { if (person == null) { throw new ArgumentNullException(nameof(person)); } // Or the following //person = person ?? throw new ArgumentNullException(nameof(person)); Console.WriteLine($"FullName: {person.FirstName} {person.LastName}"); }
With C# 10,
static void PrintFullName(Person person) { ArgumentNullException.ThrowIfNull(person); Console.WriteLine($"FullName: {person.FirstName} {person.LastName}"); }
You have to write some extra code (even though it's just a one-line) to achieve the goal. With C# 11.0, we can basically skip that line by doing something like below.
static void PrintFullName(Person person!!) { Console.WriteLine($"FullName: {person.FirstName} {person.LastName}"); }
Note the bang-bang operator, !! positioned after the parameter name. This will cause the C# compiler to emit null checking code for that parameter behind the scene. When multiple parameters contain the bang-bang operator, !!, null checks will occur in the same order as the parameters are declared.
And if we pass null to this method, we will get the exception we used to throw explicitly before.
Unhandled exception.System.ArgumentNullException: Value cannot be null. (Parameter 'person') at<PrivateImplementationDetails>.Throw(String paramName) at<PrivateImplementationDetails>.ThrowIfNull(Object argument, String paramName)
Do try out C# 11.0!
Happy Coding.
No comments:
Post a Comment