What’s new in C# 8?

By | November 27, 2017

1. Non-Nullable & Nullable Reference Types

Values types and reference types are the two variables mostly used in C# development. Values types are the likes of int, char, double, enum and struct which cannot take on the value of null (Yes there are nullable values type) whereas reference types (any object such as string) have always been able to take on a null value and have null as the default.

With C# 8, there will be a project level setting to enable validation of nullable references. Code such as

String s = null;

Will cause a warning because String cannot take on a value of null. Instead the code

String? s = null;

Moreover, this code would also throw a warning because of Console.

2. New Lightweight Classes: Records

My favorite, records help to create POCO type objects and also solve a key problem around comparing equality between objects. For example:

Creating a record type for a bank account might look like

class BankAccount(Guid Id, string Name, decimal Balance)

I personally find it a nice shorthand way to create simple classes.


3. Default Interface Implementations

Being a developer, versioning interface can be a bit annoying because it requires that new method on the interface to be implemented on all the objects which implement the interface. Default interface implementations allow specifying an implementation in the interface so long as it is implemented as a function of existing methods on the interface. The simplest form of this feature is the ability to declare a concrete method in an interface, which is a method with a body.

interface IA
void M() { WriteLine(“IA.M”); }

class that implements this interface need not implement its concrete method.

class C : IA { } // OK
IA i = new C();
i.M(); // prints “IA.M”

The final override for IA.M in class C is the concrete method M declared in IA. Note that a class does not inherit members from its interfaces; that is not changed by this feature:

new C().M(); // error: class ‘C’ does not contain a member ‘M’

Category: C#

Leave a Reply

Your email address will not be published. Required fields are marked *