Null coalescing assignment
The null coalescing operator, ??
, has been extended in C# 8 to support assignment. A popular usage for the null coalescing operator involves the parameter checks at the beginning of a method, like in the following example:
class Person { Â Â Â Â public Person(string firstName, string lastName, int age) Â Â Â Â { Â Â Â Â Â Â Â Â this.FirstName = firstName ?? throw new ArgumentNullException(nameof(firstName)); Â Â Â Â Â Â Â Â this.LastName = lastName ?? throw new ArgumentNullException(nameof(lastName)); Â Â Â Â Â Â Â Â this.Age = age; Â Â Â Â } Â Â Â Â public string FirstName { get; set; } Â Â Â Â public string LastName { get; set; } Â Â Â Â public int Age { get; set; } }
The new assignment allows us to reassign the reference whenever it is null, as demonstrated...