SHARE:

Introducing C# 9: Improved target typing

Introduction

C# 9 brings a better target typing: “In C# 9.0 some expressions that weren’t previously target typed become able to be guided by their context.” – Microsoft – https://devblogs.microsoft.com/dotnet/welcome-to-c-9-0/#improved-target-typing

Let’s see that with some examples in this article.

Target-typed new expressions

C# 9, now, allows to omit the type of the object you are instantiating. Obviously you can’t combine it with var keyword 🙂 . You can’t combine it with a ternary statement neither, it will lead to a compilation error.

Examples:

Example with Linqpad6-beta:

Target-typed with conditional operators

C# 9 brings also some improvements with target-typed conditional operators, such as ternary statements. The code below led to a compilation error prior C# 9, and now C# 9 allows this (shared type in ternary statements):

Compilation error prior C# 9:

Written by

anthonygiretti

Anthony is a specialist in Web technologies (14 years of experience), in particular Microsoft .NET and learns the Cloud Azure platform. He has received twice the Microsoft MVP award and he is also certified Microsoft MCSD and Azure Fundamentals.