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:

using CSharp9Demo.Models;
	using System;

	namespace CSharp9Demo
	{
	    class Program
	    {
	        static void Main(string[] args)
	        {
	            // Direct assignment
	            Product product = new ("VideoGame", 1);

	            // Assignment from a ternary statement
	            bool isTrue = false;
	            Product anotherProduct = isTrue ? new ("VideoGame", 1) : null; // Compilation error: CS0173 Type of conditional expression cannot be determined because there is no implicit conversion between 'new(string, int)' and '<null>'

	            // Assignment with var keyword
	            var anotherProduct = new ("VideoGame", 1); // Compilation error: CS8754 There is no target type for new(string, int)
	        }
	    }

	    public class Product
	    {
	        private string _name;
	        private int _categoryId;

	        public Product(string name, int categoryId)
	        {
	            _name = name;
	            _categoryId = categoryId;
	        }
	    }

	    public class Book : Product
	    {
	        private string _ISBN;

	        public Book(string name, int categoryId, string ISBN) : base(name, categoryId)
	        {
	            _ISBN = ISBN;
	        }
	    }
	}

#.net 5 #csharp #csharp 9 #programming-c

Introducing C# 9: Improved target typing
22.05 GEEK