Auto-property initializers
THANK YOU Microsoft for this one! Now when you declare a property, you can set it to an initial value:
public ICollection<Graphic> FriendlyShips { get; } = new List<Graphic>();
This was a welcome addition, especially for base classes that have containers (like above), and I didn't want to have to create a constructor for it just for the sake of initializing this list.
String interpolation
Instead of using ordinals: "My age = {0}", start the string with '$' and use expressions between '{' and '}':
string fullName = $"{FirstName} {LastName}";
Expression-bodied function members
Nice for single-statement functions. Instead of this:
public string FullName() { return $"{LastName}, {FirstName}"; }
you can now write:
public string FullName() => $"{LastName}, {FirstName}";
Null-conditional operators
A great new way to check for null! Before a '.', place a '?'. If the left side is null, it will stop there and return null. If not, it will continue processing the right side of the '.':
Product aProduct = myOrder?.Product;
In the above example, aProduct will be set to null if either myOrder or myOrder.Product is null. There is no need to first check for null on myOrder.
The nameof expression
This is a nice addition whenever we need the name (string version) of a class or member, particularly properties. One common use is for giving error messages that provide the name of a property:
if (IsNullOrWhiteSpace(lastName)) { throw new ArgumentException(message: "Cannot be blank", paramName: nameof(lastName)); }
Another good example is with the INotifyPropertyChanged:
public string LastName { get { return lastName; } set { if (value != lastName) { lastName = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(LastName))); } } } private string lastName;
Speaking of INotifyPropertyChange, I am really wondering if they'll ever make this an attribute we can place on Properties so we don't have to write the above boiler-plate code on each observable property.
I'm looking forward to the day I can write something like:
[Observable] public string LastName { get; set; }