Breaking

Sunday, April 18, 2021

C# 9–Target typed conditional expressions

Before C# 9, I didn’t use conditional expressions much because the different branches in the conditional couldn’t have different types.

With C# 9, this has finally changed; different types are allowed, as long as both of them convert to the target type.

Let’s explain this through an example; I have a Pet baseclass and two inherited classes Cat and Dog. If I want to use them in a conditional expression in .NET Core 3.1(using C# 8), I get the following error message:

CS8400: Feature ‘target typed conditional expressions’ is not available in C# 8.0. Please use language version 9.0 or greater.

When I upgrade to .NET 5(using C# 9) the code above works!

More information: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/target-typed-conditional-expression

No comments:

Post a Comment