Last time in our series about C# 7.3 language features, we covered tuple equality. Today we will look at unmanaged, delegate and enum type constraints. The latest Early Access Preview (EAP) versions of ReSharper 2018.2 and Rider 2018.2 come with language support for C# 7.3, do give them a try!
This post is part of a series (we will update the table of contents as we progress):
Ever since C# 2.0, when generics were introduced, it has been possible to set type constraints on generic parameters. For example, we could specify that the type constraint should implement a specific interface, and perhaps also have a parameterless constructor:
public class Repository<T>
where T : IEntity, new()
Generic type constraints can be added on class declarations, method declarations, and local functions. They allow us to constrain the types which can be used with the class or method we are creating.
Up until now, these constraints included reference type constraint (
class), value type constraint (
struct), interfaces or base class constraints, and whether a parameterless constructor should be present (
new()). With C# 7.3, three new generic type constraints are introduced (proposal):
(Fun fact: the CLR already supported these constraints, however the C# language prohibited using them. Jon Skeet has a blog post on making these constraints work in earlier C# versions.) Continue reading