Hola 🥂🥂, so in the heat of releasing the DotNet 7 preview, developers have been raving about the parameter null-checking operator popularly called the bang-bang (!!) operator😜 in C#.
So let us talk about this feature 🥶
The parameter null-checking is one of the preview features for C# 11. Preview features are features that are still in consideration and might end up making it to becoming default features of the next major release.
Prior to the release of this feature, ArgumentNullException errors could be handled using the various format below:
void Method(string name)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
// bla bla bla
}
But to try out the bang-bang operator in the c# 11 preview, you need to have at least Visual Studio 17.1 (Visual Studio 2022 Update 1) or .NET SDK 6.0.200.
At the time of writing this post, I am currently using the .NET SDK 6.0.201 to try out this feature.
You can download the SDK by clicking here
Steps To switch Into the preview mode and use the bang-bang operator:-
- Open the “*.csproj” file >> and add a LangVersion element like the one below
<PropertyGroup>
<LangVersion>preview</LangVersion>
</PropertyGroup>
- Now you can use the code below:-
//Now you can you the !! operator
void Method(string name!!)
{
/* it would automatically throw the ArgumentNullException error if name is null */
}
// instead of this code
void Method2(string name)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
// bla bla bla
}
They have been a little bit of friction in terms of developers in the DotNet community accepting this feature.
Some advocated for the use of a notnull keyword which seems to be more understandable and intuitive at a glance.
To check out more about some of the preview features click this.
Thanks for reading 🥂
PS :- This feature later got removed you can look out for more details here.