The preview 1 of dotnet 10 and therefore the next iteration of the C# language is right in front of our doorsteps. So let's have a look at one of the first potential additions to the language: Null-conditional assignment.
The basic problem it tries to solve is something like this: Imagine you have a variable which might be null
. If it isn't you want to assign a property. The way to do it now is:
MyObject? myObj = CallThatMightCreateMyObject();
if (myObj is not null)
{
myObj.Property = 100;
}
The proposal tries to tackle exactly this - the code above can be shortened to:
MyObject? myObj = CallThatMightCreateMyObject();
myObj?.Property = 100;
So if myObj is not null
the assignment will be called, otherwise not. Basically, a fancy compiler sugar for the same code as above.
To be absolutely clear, you can also do those "beautiful" assignments:
MyDeeplyNestedObj? m = FromSomewhere();
m?.A?.B?.C?.D = "Foo Bar";