In this article, we'll discuss about several new C# 10 features that will make it easier for you to develop code that is faster, clearer, and more expressive. One of the most established and rapidly expanding programming languages in the world is C#. Some new features in C# 10 improvements listed here will make it easier and faster for developers to produce cleaner, more readable code. With an example, we'll look at each one separately.
C# 10 is supported on .NET 6 and Visual Studio 2022. Some of the top new features in C# 10 are listed below:
Null Parameter Checking.
Record struct.
Record types can seal to string.
Let’s look at each of these features in C# 10.
Constant interpolated strings:
In order to use string interpolation, you must first place a $ character right before the string. After that, instead of giving separate arguments for each formatting element, you may simply incorporate those arguments right into the interpolated string. An opening and closing brace ( { } ), contains an interpolation expression.
( To concatenate const strings in C# 9.0 or previous versions, we must use the "+" operator). let’s see the example.
const string a = "Md Fida";
const string b = a + " Hussain " ;
Console.WriteLine(a);
Console.WriteLine("my full name is: " +b);
Now
in C# 10, we can use the interpolated sign $
to combine our const
strings. Below is an example of how text can be substituted for a string
literal using string interpolation.
Example:
const string a = "Welcome to";
const string b = $"{a} CodeToSolutions";
Console.WriteLine(a);
Console.WriteLine("This article greets: " +b);
Console.ReadLine();
Output:
This article greets: Welcome to CodeToSolutions
This implementation can only be carried out if all strings are designated as const, otherwise, it will not work. Let’s see an illustration.
Example:
const string a = "This is a const string";
string b = "This is not constant string";
//An exception will be thrown by this line.
const string result = $"{ a } . { b }";
This code will throw an exception and not produce anything. Therefore, only const strings can be used with this interpolation capability.
Null Parameter Checking:
Users can benefit from Null Parameter Checking, a new feature in C# 10, by increasing code flexibility and preventing errors like "Object Reference Not Set to an Instance of an Object." The new C# version has made this problem simpler, Put two exclamation points immediately after the parameter's name. Automatic null checking will take place. The ArgumentNullException would immediately be thrown for null values.
In C# 9 or previous versions, we used to perform null checking like the code example below:
public InsertData(string name, string email)
{
if (name == null)
{
throw new ArgumentNullException(" name ");
}
...
}
In C# 10 If you add !! to the end of your parameter (name in the example below), it will automatically check for null values for you.
public InsertName(string name, string email !!)
{
...
}
Global using in C# 10 :
In C# version 10.0, a new feature known as the global using directive was introduced. This feature enables developers to import and make a global namespace declaration available to all files in an application from any of the project's files. This feature is meant to keep the code organized and prevent the use of the same namespace in many files. For instance, all you need to do is declare globally once if you use the System.Collections.Generic namespace in multiple .cs files.
The global using namespace is declared in the code below.
global using System.Collections.Generic;
global using System.Linq;
We can put global usings in any .cs file, including Program.cs or a specifically named file like GlobalUsings.cs.
So, use global using just once in a central file of the projects and access it anywhere you want.
Extended property patterns:
Extended property patterns make the code easier to read When accessing a child property from a parent property. An extended property pattern is particularly helpful when dealing with nested properties. We can use . token to access members in a property pattern. This is called extended property patterns.
Below is an example of extended property to understand the concept.
File : Employee.cs
public record Employee(int employeeID, string Name, Employee? employee = null);
File : Program.cs
In C# 9 or previos versions we get the propery like this.
var EmployeeInfo = new Employee(1009, "david");
var employee = new Employee(1009, "david", EmployeeInfo);
if (employee is { employee: { Name: " david " } })
{
...
}
Now, This can be expressed as Name is used as a property in C# 10.
if (employee is { employee.Name: "david" })
{
...
}
File-scoped namespace:
We can specify a single namespace for the entire file using the new file-scoped namespace declaration in C# 10. We are unable to define any more namespaces once the file-scoped namespace has been declared. We can now include the file-scoped namespace as a statement, followed by a semicolon “;” without the curly braces { }.
In C# 9 or previous versions of the C# language, we used to declare the namespace as:
namespace MyConsoleApp.Services
{
class DemoClass
{
...
}
}
In C# 10, we can follow the new way of a namespace declaration as shown below:
// File-scoped namespace declaration
namespace MyConsoleApp;
However, C# 10 does support file-scoped namespace, as illustrated below: Take note of the braces being removed.
namespace MyConsoleApp.Services;
class DemoClass
{
...
}
Record types can seal to string:
Since C# 10's release, you can add a sealed modification to a record type's ToString() override to stop the compiler from generating a ToString() implementation for any derived record types. The sealed ToString() method makes a guarantee that all record types descended from the common base record type use the ToString() method.
In Simple words, we can say when we override the ToString method while working with a record type, we can apply the sealed modifier.
public record Person
{
public string FirstName { get; init; }
public string LastName { get; init; }
public sealed override string ToString()
{
return $"My name is {FirstName} {LastName}";
}
}
public record Students : Person
{
public override string ToString() //
Error CS0239 'Student.ToString()': cannot override inherited member
'Person.ToString()' because it is sealed
{
return $"My
name is {FirstName} {LastName}";
}
}
Assignment and declaration in the same deconstruction:
Users could either declare new variables in deconstruction or assign values to already-existing variables in C# 9 or previous versions of C#. It was not possible to declare a new variable and then assign a value to an already-existing variable at the same time. Now that this limitation has been removed in C# 10, you can define a new variable and assign a value to it all in one operation.
In C# 9 or the previous version this was the process as shown below:
(string firstname, string lastname)
= var student;
Or
string firstname;
string lastname;
(firstname, lastname) = student;
Now, in C# 10 we can follow the new way of an assignment declaration in the same deconstruction as shown below:
string firstname;
(firstname, string lastname) = student;
Conclusion :
In this article, we learned about some new C# 10 features that were included with the release of the new version of C#. Some of these improvements seem to be very important because they seem to change how we approach and develope C# projects.
I hope you found this article to be interesting and helpful. Please add your opinions and suggestions to the discussion below.
Share This Post
Support Me