Features of C-Sharp 9

04 januari 2021 om 10:00 by ParTech Media - Post a comment

In this blog post, let’s take a look at the 4 important and newly released features in C# 9.0. Even though the original update was planned to ship out 29 new features, not all of it was released as planned.

All these 4 features have been released with the intention to make the lives of the programmers easier and more efficient at the same time. Let’s dive right in

Table of Contents

  1. Improved Pattern Matching
  2. Records
  3. Target typing improvements
  4. Top - Level programs
  5. Verdict

Improved Pattern Matching

Most of the data processed in C# is increasingly defined by its shape and patterns. The ability to declare the behavior of data based on its pattern is growing constantly. We have been seeing this shift since the inception of pattern matching in C# 7.

Here’s an example scenario to help you understand this better

Let’s say that you want to use pattern matching to determine the discount price for a person based on his number of visits to the store -

  • If he has visited your store for less than 12 times you offer them a discount of 5%.
  • If the person has visited between 12 and 20 times, you offer a discount of 15%
  • If the person has visited your store more than 20 times, your discount is 20%

Here is the code for it in C#

static int CalculateDiscount(Person person)

{

  return person switch

  {

​    var p when p.visit <= 12 => 5,

​    var p when p.visit > 12 && p.visit <= 20 => 15,

​    var p when p.visit > 20 => 20

  };

}


When you look through it, you’ll realize that it has quite a bit of unwanted lines in it.

With the advancement of pattern matching in C# 9, we can express switch expressions in terms of relational operators and logical expressions.

Here’s how the improved version looks

static int CalculateTicketPrice(Person person)

{

  return person when person.visit switch

  {

​    <= 12 => 5,

​    \> 12 and <= 20 => 15,

​    \> 20 => 20

  };

}

Records

This is a long-awaited feature for many programmers who have been using C# for their development needs. The properties of all the records are read-only by default and they allow you to compare structural equality.

Records are of two types -

  1. Value type
  2. Reference type

Records are what bridge the gap between class and Struct types in C#.

The equality of a class is determined by its underlying reference, rather than the added value of its members. On the other hand, struct gets its value when determining equality.

In essence, your compiler ends up overriding the default equity behavior of a class, even though most of its value semantics would be highly desirable for implementation.

Records have value semantics while allowing you to pass your class by reference. They are immutable and their state never changes during the process of referencing. Whenever an object changes its state, the new members are updated and a copy of the record is created.

In simple words - each record represents the state of an object at a very specific point in time.

Target Typing improvements

In C# 9, some expressions that weren’t previously target typed, can be guided by their context. Just like the first feature, let’s take a look at this with an example

using CSharpDemoProj.Models;

using System;

namespace CSharpDemoProj

{

  class Program

  {

​    static void Main(string[] args)

​    {

​      Product prod = new ("VideoGame", 1);

​       

​      bool isTrue = false;

​      Product anotherProduct = isTrue ? new ("VideoGame", 1) : null;



 // You will get a Compilation error in here.    

​    

​      var anotherProduct = new ("VideoGame", 1); 



// you will get another Compilation error here = There is no target type for new(string, int)

​    }

  }



  public class prod

  {

​    private string _name;

​    private int _categoryId;



​    public prod(string name, int categoryId)

​    {

​      _name = name;

​      _categoryId = categoryId;

​    }

  }



  public class Book : prod

  {

​    private string _ISBN;



​    public Book(string name, int categoryId, string ISBN) : base(name, categoryId)

​    {

​      _ISBN = ISBN;

​    }

  }

}


This example showed a compilation error before the birth of C# 9. But after C# 9, you are allowed to work on it without any errors. Target typing is aimed to make your life as a programmer one step easier.

C# 9 allows you to omit the new expression as long as the left-hand side of the assignment operator has the type listed in it. For example, this update should make the following declaration legal in C# 9

Product1 prod = new():

Top Level programs

Top level programs is a dream come true for new programmers in C#. It helps them omit the basic code or “ ceremonial intro “ that usually comes with the basic programs.

For example, let’s consider a scenario, where you are required to write the line “I work in Partech “

Even though it is just a simple line, you need to write five lines of code to display it on the screen. Here is how you will have to write the code, to display this simple message.

using system;

namespace ConsoleApp

{

  class Program

  {

​    static Main(string[] args)

​    {

​      Console.WriteLine("I work in Partech");

​    }

  }

}

All these braces and lines of code for a single message. That seems absurd, doesn’t it!

So this is exactly where your top-level programs can help you get rid of unnecessary lines of code. The concept of top-level programs helps omit all these lines and bring it into something simple, like this

Using system;

Console.Writeline( “ I work in Partech“ );

You can skip all the unnecessary lines of code ( although they are essential in large programs ) to make it simple. As stated before, top-level programs are extremely useful for programs where you are going to run nothing more than a single snippet of C#.

This feature makes C# easy to use for beginners and novice programmers. They will not be intimidated any more when they start working with C# applications and other stuff.

Verdict

The C# is constantly improving as a programming language and the recent updates serve as proof of that. Microsoft is shaping up this language to be a versatile and highly valid option for new and experienced programmers. Features like Record types and Top Level Programs solidify its path into a better future and make C# 9 reliable as a programming language. If you’ve been thinking about diving into C# for some time, you should get into it right now.

Nieuwste