Exploring Target Typing and Covariant Returns in C# 9
C# 9 introduced several powerful features designed to enhance code efficiency and flexibility. In previous discussions, we’ve explored topics such as record types, static anonymous functions, relational and logical patterns, and top-level programs. In this article, we’ll focus on two more valuable capabilities: target typing and covariant returns, both of which further improve the language’s ability to streamline development and boost code readability.
Target typing is a feature that allows an expression to automatically infer its type based on the context in which it is used, eliminating the need to specify the type explicitly. In C# 9, this functionality has been extended to new expressions and conditional operators, making the language more concise and reducing the redundancy in type declarations. This can be especially useful in scenarios where the type can be easily inferred from the surrounding code, thus improving both developer productivity and code clarity.
Another important feature introduced in C# 9 is support for covariant return types. This allows a method to override another method and declare a return type that is more derived, or more specific, than the original method’s return type. This is particularly helpful when working with inheritance hierarchies, as it enables more flexible and precise overrides without requiring changes to the method signature. It also enhances the ability to design polymorphic systems where return types can be tailored to specific needs without breaking existing functionality.
To follow along with the examples in this article, you’ll need Visual Studio 2019 installed on your system. If you haven’t installed it yet, you can download it from the official website. C# 9.0 is supported in Visual Studio 2019 version 16.9 Preview 1 or later, as well as the .NET 5.0 SDK. Once you have Visual Studio set up, you can begin by creating a .NET Core console application project, which will allow you to experiment with target typing and covariant returns directly in your own development environment.