C# Amazing New Features

In this article, we are going to learn about C# amazing new features available in recent releases.

For this article, we are picking a couple of the most exciting features of C# versions 10, 11 and 12. So, let’s start.

File-scoped Namespace Declaration

This feature is one of the most interesting features of C# 10.

Here is the block-scoped namespace, we used in earlier versions:

namespace ConsoleApp1
{
    public class Product
    {
    }
}

We can now re-write the code snippet using file-scoped namespace:

namespace ConsoleApp1;

public class Product
{
}

Here, we remove the extra brackets and this applies proper indentation to the code.

Interpolated string handler

Another interesting feature of C# 10. The string interpolation allows programmers to embed arguments into the interpolated string.

Before C# 10:

string message = "Welcome to C# Programming";
Console.WriteLine("Hello !," + message);

C# 10 onwards with string interpolation:

string message = "Welcome to C# Programming";
Console.WriteLine($"Hello !, {message}");

In string interpolation, we use the $ sign at the beginning and keep all the arguments within the interpolated string. Here, we put {message} within the string.

Required Members

If we use require modifiers to the properties or fields then the constructors and callers must initialize those values. The feature is available from C# 11.

Let’s look at the syntax:

class Product
{
    public required string Name;
    public required int Cost;
}

Here, we have a class which contains two members and both members with required modifiers.

Next, we will initialize the values:

var product = new Product { Name = "Book", Cost = 200 };

This code will work perfectly, as we are initializing the the members.

However, if we initialize only one member, then we get the error:

So, if we have members with required modifiers then those members need to be initialised to avoid compile time error.

File local types

With the release of C# 11, the file keyword is a modifier type. So, using the file keyword, we can avoid naming collisions.

Let’s see the syntax of the file keyword:

file class Student
{
    public string Name { get; set; }
}

Here, the class Student is limited to the file where we are declaring this.

Let’s consider this with another example:

var obj = new Student();

file class Student
{
    public string Name { get; set; }
}

Here, we are creating the object of the class Student in the same file and the code will work without any error.

However, if we move the Student class to a separate file and then if we create the object of this class from another file, this code will not work even if both the files are in the same namespace. Because, as per the rule the file keyword allows the visibility of the class to the file in which it is defined.

Class file:

file class Student
{
    public string Name { get; set; }
}

Program.cs file:

var obj = new Student();

Here, this code will not work as they are in two different files.

List Pattern

List Pattern is a pattern-matching feature available in C# 11. So, with a list-pattern, we can match a list or an array against the sequence of the patterns.

Let’s consider the code snippet:

int[] numbers = { 1, 2, 3 };
Console.WriteLine(numbers is [1, 2, 3]);

Here, we have an array of integers and with a list pattern, we are matching with the same integers in the same sequence. So, this will be true.

Next, consider the code snippet:

int[] numbers = { 1, 2, 3 };
Console.WriteLine(numbers is [1, 2, 4, 3]);

Here, we are not matching with the same sequence, so the output will be false

Finally, we will see one more example:

int[] numbers = { 1, 2, 3 };
Console.WriteLine(numbers is [1, <=2, 2 or 3]); 

In pattern matching first item is 1 which matches with the first element of the given array. The second item says, it should be less than or equal to 2 and this also matches with the second item in the numbers array. And, the same for the 3rd item.

Finally, the matching pattern satisfies the condition and hence it will return true.

Primary Constructor

The Primary Constructor concept came into existence in C# 12 along with .NET 8. Primary Constructor enables us to remove the constructor method and add its parameters to the class declaration itself.

public class Product(string name)
{
    public string Name { get; set; } = name;
}

Finally, while initializing the the class with primary constructor, we need to pass the parameter.

var product = new Product("Laptop");
Read more about Primary Constructor: Primary Constructor in C# 12

InLine Arrays

C# 12 introduces a new way to create an array. For this, we use System.Runtime.CompilerServices.InlineArray namespace as an attribute and then we need to specify the size of the array.

Let’s see the syntax to use inline array:

[System.Runtime.CompilerServices.InlineArray(5)]
public struct InLineArray
{
    private int _Arrelement;
}

Here, we are using an attribute which specifies the array size as well.

Next, we can add items to this array:

var inLineArr = new InLineArray();
inLineArr[0] = 0;
inLineArr[1] = 1;
inLineArr[2] = 2;
inLineArr[3] = 3;
inLineArr[4] = 4;

In the code snippet, we are adding 5 items to the array, this is because we have an array which can store a maximum of 5 elements.

Finally, we can print array items over the console:

foreach (var item in inLineArr)
{
    Console.Write($"{item} ");
}

Alias for Any Type

Alias any type is a feature introduced in C# version 12. This feature allows us to use aliases of any type.

Let’s see the syntax, add this line in the namespace area:

using AddParam = (int a, int b);

We will create a method which accepts AddParam as the parameter.

public int Method1(AddParam param)
{
    return param.a + param.b;
}

We have AddParam as an alias, which we already have in the namespace area. So, to execute and print the value, we use AddParam alias and assign 2 integer values:

AddParam param = (50, 120);
int result = Method1(param);

Here, the AddParam alias have two integer values, and we pass the AddParam alias to the Method1() as a parameter. Finally, it executes and prints the value. 

Conclusion:

In this article, we learnt some of the amazing features of C# from recent releases. So, mainly we focus on C# 10, 11 and 12 versions. Some of the interesting features we covered are file-scoped namespace, file keyword, alias of any type, primary constructor etc.

Hope these new C# features will give you more benefit to you.

Leave a Comment

RSS
YouTube
YouTube
Instagram