Target Typing And Shared Types In C# 9.0

Introduction

In today’s article, we will look at Target Typing Improvements and Shared Types in C# 9.0. C# 9.0 has been introduced with .NET 5.0. We will look at another cool feature that C# 9.0 brings to us, which is target typing and shared types and how these can be used.

Using C# 9.0

Microsoft recently announced the availability of a .NET 5 release candidate at Microsoft Ignite 2020. This included the latest features in C# 9.0. In order to code in .NET 5.0, we would need to install the latest preview of Visual Studio 2019 (Version 16.8.0 Preview 3.1). As I had read about some cool features in C# 9.0including the improvements to target typing and shared types, I downloaded and installed the required version as below,

Target Typing and Shared Types in C# 9.0

In previous versions of C#, if the return value types do not match, we get an error. Even if the types share the same type, we will still get an error. However, in C# 9.0, if the return values have a shared type, there is no warning or error. Let us look at this with an example.

Using Target Typing and Shared Types

Let us create a console application in Visual Studio 2019 (Version 16.8.0 Preview 3.1) as below,

Target Typing and Shared Types in C# 9.0

Target Typing and Shared Types in C# 9.0

Target Typing and Shared Types in C# 9.0

Now, add the below code,

using System;
using System.Collections.Generic;

namespace ConsoleAppTargetTyping
{
    class Program
    {
        static void Main(string[] args)
        {
            var values = GetTaxPercentRates(true);
            foreach (var val in values)
            {
                Console.WriteLine($"Value is {val}");
            }
            Console.ReadKey();
        }

        public static IEnumerable<int> GetTaxPercentRates(bool IsSingle)
        {
            return IsSingle ? new List<int>
            {
                5,
                8,
                11
            } : new[]
            {
                2,
                3,
                5
            };
        }
    }
}

Here you will see that there is an error indicated in the return statement. Although, both the List<int> and array are IEnumerable<int>, we cannot set them separately as done above. We get the below error,

Target Typing and Shared Types in C# 9.0

We can fix this code as below,

using System;
using System.Collections.Generic;

namespace ConsoleAppTargetTyping
{
    class Program
    {
        static void Main(string[] args)
        {
            var values = GetTaxPercentRates(true);
            foreach (var val in values)
            {
                Console.WriteLine($"Value is {val}");
            }
            Console.ReadKey();
        }

        public static IEnumerable<int> GetTaxPercentRates(bool IsSingle)
        {
            return IsSingle ? (IEnumerable<int>)new List<int>
            {
                5,
                8,
                11
            } : new[]
            {
                2,
                3,
                5
            };
        }
    }
}

Here we have cast the first value to IEnumerable<int> and all works fine.

IEnumerable

Next, we will change the properties of the project and set the Target Framework to .NET 5.0, as below,

Target Typing and Shared Types in C# 9.0

After we change the framework to .NET 5.0 and use C# 9.0, we can revert to the old code as below,

using System;
using System.Collections.Generic;

namespace ConsoleAppTargetTyping
{
    class Program
    {
        static void Main(string[] args)
        {
            Employee employee = new(1, "John Smith", 30);
            var values = GetTaxPercentRates(true);
            foreach (var val in values)
            {
                Console.WriteLine($"Value is {val}");
            }
            Console.ReadKey();
        }

        public static IEnumerable<int> GetTaxPercentRates(bool IsSingle)
        {
            return IsSingle ? new List<int>
            {
                5,
                8,
                11
            } : new[]
            {
                2,
                3,
                5
            };
        }
    }

    public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }

        public Employee(int id, string name, int age)
        {
            Id = id;
            Name = name;
            Age = age;
        }
    }
}

When we run the above code, we get the following output,

ConsoleApp

Also, note that we have created an instance of the Employee class (although not used in this example) without specifying the type after the new keyword. This is because we specify the type on the left-hand side of the assignment statement. This is known as the target-typed new expression. This is also a new feature of C# 9.0.

Summary

In this article, we looked at the improvements in target typing and shared types in C# 9.0. We could argue that this is not an incredibly significant change. However, these are the new changes that make C# a much more friendly language to program in. Happy Coding!


Similar Articles