Some Cool Features In C# 10

Introduction

In today’s article, we will take a look at a few new cool features which are part of C# 10. These features might seem small, but they help to improve the overall readability and efficiency of our code. So, let us begin.

Creating a C# 10 console application

The first step is to create a simple C# console application in Visual Studio 2022 community preview edition as below.

Some Cool Features In C# 10

Some Cool Features In C# 10

Some Cool Features In C# 10

Some Cool Features In C# 10

Some Cool Features In C# 10

Now, we add a new class called “Employee”.

Some Cool Features In C# 10

Add the below code to the respective files.

Employee.cs

// No indent namespace declaration C# 10
namespace CoolCSharp10Features;
public class Employee {
    public Employee() {
        Console.WriteLine("Creating the Employee class");
    }
    public int Id {
        get;
        set;
    }
    public string ? Name {
        get;
        set;
    }
    public int Age {
        get;
        set;
    }
}

Program.cs

// Global using C# 10
global using CoolCSharp10Features;
var emp = new Employee {
    Id = 5, Name = "John Doe", Age = 30
};
Console.WriteLine($" Employee Id: {emp.Id}, Name: {emp.Name}, Age: {emp.Age}");
// Declared and assigned Deconstruction C# 10
var kvPair = new KeyValuePair < int,
    int > (1, 2);
int a = 0;
(a, int b) = kvPair;
Console.WriteLine($" A: {a}, B: {b}");
// Constant string interpolation
const string greetingsOne = "Hello ";
const string greetingsTwo = " to all readers";
const string greetings = greetingsOne + greetingsTwo;
Console.WriteLine(greetings);

Let us analyze the new features we see in these two files. In the “Employee.cs” file, we see that we declare the namespace without the opening and closing brace, and hence the namespace is for the complete file. This helps to reduce indentation in the file.

In the “Program.cs” file, we are using the “global” keyword before the using statement. This is used when we want to use this using statement in many places and rather than repeating it in many files, we just declare it as global.

We also see that we can use both previously declared and assigned variables together when we deconstruct a key-value pair. This was not allowed before. Finally, we see that we can use string interpolation while declaring constants.

When we run this application, we see the below output.

Some Cool Features In C# 10

Summary

In this article, we took a look at some new cool features which are part of C#10. These features might seem trivial, but they help to improve our code in terms of readability and efficiency. Happy coding!


Similar Articles