I'm sure years from now I'll look back and find it odd I wrote an article on such a basic C# feature. However, I'm writing this now mostly to force myself to remember to use this new feature.
Quite often we need to check if an object is null, and if so, assign it to something. Looks like this:
void DoSomething(UserRepository userRep) { if (userRep == null) { userRep = new DefaultUserRepository(); } userRep.ReadSomeUserData(); }
Using Null-Coalescing Assignment
With the new Null-Coalescing Assignment feature we can simplify the first part as follows:
void DoSomething(UserRepository userRep) { userRep ??= new DefaultUserRepository(); ...