The very best new options of C# 14


Accessible as part of .NET 10, which was launched final November, C# 14 brings a plethora of recent options and enhancements that make it simpler to put in writing environment friendly, excessive performant code. Simply as we walked by means of the brand new options and enhancements in C# 13 and C# 12, on this article we’ll take an in depth take a look at a few of the finest new options in C# 14.

To work with the code examples offered on this article, you need to have Visible Studio 2026 or a later model put in in your system. In case you don’t have already got a duplicate, you’ll be able to obtain Visible Studio 2026 right here.

File-based apps

Assist for file-based apps is maybe essentially the most placing new function on this launch of the C# programming language. Till C# 14, we’ve needed to observe a multi-step course of to run a minimal .cs file. Not solely was this a multi-step course of, however it incurred vital extra overhead since you needed to create an answer file and a challenge file to run your software. Even when all you wished to do was carry out a fast calculation or course of a bit of information shortly to check your code, you needed to create extra recordsdata chances are you’ll not want later. Now not.

With C# 14, now you’ll be able to run a C# file straight from the command line with no need a challenge or resolution file.

Allow us to perceive this with a code instance. Contemplate a file named Demo.cs that accommodates the next code.

Console.WriteLine("This can be a pattern textual content");
DateTime dateTime = DateTime.UtcNow.Date;
Console.WriteLine($"At this time's date is: {dateTime.ToString("d")}");

You’ll be able to execute this system utilizing the next command on the console window.

dotnet run Demo.cs

When this system is executed, you’ll see the next textual content displayed on the console.

Foundry

Word which you could create file-based apps that reference NuGet packages and SDKs utilizing preprocessor directives, with no need a challenge or resolution file.

Extension members

Extension members are a brand new function in C# 14 that allow you to declare extension properties in addition to extension strategies. As well as, extension members make it simpler to declare extension strategies than in earlier variations of C#. Earlier than we dive into extension members, let’s first perceive extension strategies.

Within the C# programming language, extension strategies are a function that allows you to increase the capabilities of courses with out the need of inheritance. You don’t want to create subclasses to make use of extension strategies, neither is it obligatory to change or recompile current class definitions. Along with bettering code readability, extension strategies enable you to add new strategies to your current sorts (i.e., courses, structs, data, or interfaces). By the way, extension strategies have been first applied in C# 3.0.

There are quite a few extension strategies in .NET that permit you to increase the querying capabilities of each System.Collections.IEnumerable and System.Collections.Generic.IEnumerable by utilizing the LINQ customary question operator. Whilst you can reap the benefits of extension strategies to increase a category or an interface in C#, you can not override their strategies. Extension strategies may help you to increase the performance of sorts even when they’re sealed, such because the String class in C#.

For instance, the the place() extension technique is outlined within the Enumerable static class pertaining to the System.Linq namespace. The next code snippet creates an occasion of the the place() extension technique:

public static IEnumerable The place(
    this IEnumerable supply, 
    Func predicate)

Word the usage of the this key phrase. Previous to C# 14, to implement an extension technique, you needed to create a static technique and move the this reference as a parameter to the strategy. In C# 14, the code snippet above may be changed utilizing an extension block, with out the necessity of specifying the this parameter. That is proven within the code snippet given under.

extension(IEnumerable supply)
{
    public IEnumerable 
     The place(Func predicate)
}

The flexibility to outline extension members has different benefits as properly. Word that an extension member requires two kinds of info, i.e., the receiver to which the member ought to be utilized and any parameters it would want if the member is a technique. With the brand new extension member syntax, you’ll be able to outline an extension block after which write the receivers as wanted. Most significantly, this new syntax allows you to outline a receiver to your extension member that doesn’t require any parameter, i.e., if you happen to’re utilizing an extension property. 

Moreover, by utilizing the brand new syntax, you’ll be able to logically group extensions that apply to the identical receiver. You’ll be able to then outline a brand new extension block if the receiver adjustments. Furthermore, the static class through which you write your extension blocks or extension strategies (if you happen to’re utilizing an earlier model of the C# language) can comprise each the extension strategies that require the this parameter and the extension members grouped inside extension blocks, as proven within the C# 14 code itemizing given under.

public static class StringExtensions
{
    extension(string worth)
    {
        public bool ContainsAnyDigit()
        {
            if (string.IsNullOrEmpty(worth))
                return false;
            return worth.Any(char.IsDigit);
        }
        public bool ContainsAnySpecialCharacter()
        {
            if (string.IsNullOrEmpty(worth))
                return false;
            return worth.Any(c => !char.IsLetterOrDigit(c));
        }
    }

    public static bool IsNullOrEmptyOrWhiteSpace(this string str)
    {
        return string.IsNullOrWhiteSpace(str);
    }
}

Within the previous code snippet, the extension technique IsNullOrEmptyOrWhiteSpace makes use of the legacy syntax (i.e., it requires the this parameter), whereas the extension strategies ContainsAnyDigit and ContainsAnySpecialCharacter use the brand new syntax.

You’ll be able to learn extra about extension members in C# 14 right here.

Enhancements to the nameof operator for unbound generics

C# 14 brings enhancements to the nameof key phrase by supporting unbound generic sorts (e.g., ListingDictionary). Now that nameof can take an unbound generic kind as an argument, you not have to outline dummy kind arguments (akin to Listing) merely to acquire the sort title “Listing.”

Allow us to perceive this with a code instance. Within the following piece of code, you’ll have to specify the sort argument for the forged to work completely.

string typeNameList = nameof(Listing);
string typeNameDictionary = nameof(Dictionary);

With C# 14, unbound generics work straight. You not have to specify the sort explicitly, as proven within the code snippet given under.

string typeNameList = nameof(Listing);
string typeNameDictionary = nameof(Dictionary);

Therefore, with C# 14, the next traces of code will work completely.

Console.WriteLine(nameof(Listing));
Console.WriteLine(nameof(Dictionary));

Person-defined compound task operators

C# 14 comes with help for compound task operators. This function allows you to write code much like x += y as an alternative of getting to put in writing x = x + y, as you do within the earlier variations of the language. You should utilize compound task operators in C# 14 to overload +=, -=, *=, /=, %=, &=, |=, ^=, <<=, and >>= operators.

Contemplate the next code snippet that creates a ShoppingCart class through which the += operator is overloaded.

public class ShoppingCart
{
    public int TotalQuantity { get; non-public set; } = 0;
    public decimal TotalAmount { get; non-public set; } = 0m;
    public void operator +=(int amount)
    {
        TotalQuantity += amount;
    }
    public void operator +=(decimal quantity)
    {
        TotalAmount += quantity;
    }
}

The code snippet under exhibits how you need to use the ShoppingCart class.

public class ShoppingCart
{
    public int TotalQuantity { get; non-public set; } = 0;
    public decimal TotalAmount { get; non-public set; } = 0m;
    public void operator +=(int amount)
    {
        TotalQuantity += amount;
    }
    public void operator +=(decimal quantity)
    {
        TotalAmount += quantity;
    }
}

Because of user-defined compound task operators, we get cleaner, easier, and extra readable code.

Set TargetFramework to .NET 10

Naturally, you will need to have .NET 10 put in in your pc to work with C# 14. If you wish to change your current tasks to make use of C# 14, you will have to set the TargetFramework to .NET 10 as proven within the code snippet given under.


  
    Exe
        preview
    net10.0
    allow
    allow
  

You’ll be able to study extra concerning the new options in C# 14 right here and right here.

The C# programming language has improved considerably since its preliminary launch as a part of Visible Studio .NET 2002. That was a time whenever you needed to write lots of verbose code to create C# packages. The brand new options launched in C# 14 promise to spice up your productiveness and enable you to write cleaner, extra maintainable, and extra performant code. Whether or not you’re constructing an enterprise software, a cell software, or an online software, this new model of C# offers you with all you want to create world-class modern functions.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles