Introduction
In today’s article we will look at two new features introduced with C# 8.0.The first is called the Null-coalescing assignment feature and the second is the enhancement to interpolated verbatim strings. C# 8.0 is supported on .NET Core 3.x and .NET Standard 2.1.
Creating a simple Console application to demo
We start by creating a simple console application using Visual Studio 2019 community edition. The framework used is .NET Core 3.1.
In this application, we will first create a simple function to demonstrate the Null-coalescing assignment feature and then create a second function to demonstrate the enhancement to interpolated verbatim strings.
Null-coalescing assignment
This feature allows us to use the null-coalescing assignment operator which is “??=”. We can use this“??=” operator to assign the value of its right-hand operand to its left-hand operand, but this only happens if the left-hand operand evaluates to null. Let us look at the below code,
- using System;
- using System.Collections.Generic;
- namespace CSharp8Features {
- class Program {
- static void Main(string[] args) {
- Null coalescingAssignment();
- Console.ReadKey();
- }
- static void NullcoalescingAssignment() {
- List < int > values = null;
- int ? number = null;
- values ?? = new List < int > ();
- values.Add(number ?? = 10);
- values.Add(number ?? = 15);
- values.Add(number ?? = 20);
- Console.WriteLine(string.Join(",", values));
- Console.WriteLine(number);
- }
- }
- }
When we run this code, we get the below,
Here, we see that we get 10,10,10 on the first line and 10 on the second line. This is because we added the number variable three times to the list. The first time it was null and hence 10 was assigned to it. However, on the second and third “Add” function calls, we first checked if it was null before assigning (using the Null-coalescing assignment operator) a value to it. As it was not null, the values 15 and 20 were not assigned to it and each time the value of 10 was added to the list. Hence, we see the three values of 10 are added. Hence, the final value of number is also 10.
Enhancement to interpolated verbatim strings
The order of the $ and @ tokens which were used in interpolated verbatim strings can be any of the two now,
In earlier versions of C#, the $ token would have to appear before the @ token.Let us see the code below,
- using System;
- namespace CSharp8Features {
- class Program {
- static void Main(string[] args) {
- var name = "C# Corner";
- Console.WriteLine($ @ "Hi from {name}. The path is \test\path");
- Console.WriteLine(@$ "Hi from {name}. The path is \test\path");
- Console.ReadKey();
- }
- }
- }
When run, both give the same result as below,
Summary
In this article, we looked at two new features that have been introduced with C# 8.0. These are useful features and can be incorporated into our code to improve the quality of it. I will be covering more of C# 8.0 features in future articles. Happy Coding!