Monday, July 15, 2024
HomeC#What’s New in C# 13 for Builders?

What’s New in C# 13 for Builders?

What’s New in C# 13 for Developers?

TL;DR: Discover the most recent options in C# 13! From enhanced params collections to modernized thread synchronization, uncover how these updates can increase your coding effectivity and productiveness. Dive in and revolutionize your growth expertise!

Welcome to our weblog concerning the thrilling new options launched in C# 13! This newest model of C# brings a bunch of enhancements and improvements designed to empower builders to put in writing cleaner, extra environment friendly, and expressive code.

We’ll delve into the important thing options and updates that C# 13 presents. From enhanced params collections to the comfort of recent escape sequences, C# 13 is filled with instruments that make coding extra intuitive and productive.

Let’s see them intimately!

Key highlights of C# 13

Following are a number of the key highlights of C# 13:


To experiment with these options firsthand, you’ll want the most recent model of Visible Studio 2022 or the .NET 9 Preview SDK. Each choices present entry to C# 13’s cutting-edge functionalities.

Enhanced params collections

The params key phrase was beforehand restricted to arrays; now, it embraces a wider vary of assortment varieties. You should use it with System.Span<T>, System.ReadOnlySpan<T>, and collections implementing System.Collections.Generic.IEnumerable<T> and possessing an Add technique. Moreover, interfaces like System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, and extra may be utilized with params. This flexibility streamlines parameter passing for varied assortment situations.

Help for ReadOnlySpan<T>

In C# 13, the help for ReadOnlySpan<T> has been enhanced to permit assortment expressions to work immediately with this high-performance struct. ReadOnlySpan<T> is a type-safe and memory-safe read-only illustration of a contiguous area of arbitrary reminiscence. It’s allotted on the stack and might by no means escape to the managed heap, which helps keep away from allocations and improves efficiency. Assortment expressions can now work immediately with ReadOnlySpan<T>, a high-performance struct that avoids allocations. This enhancement is especially helpful for functions that require optimum efficiency.

Advantages of ReadOnlySpan<T>

  • Avoids allocations: Since ReadOnlySpan<T> is a stack-allocated struct, it avoids heap allocations, which may profit performance-critical functions.
  • Reminiscence security: It offers a type-safe solution to deal with reminiscence, guaranteeing you don’t by chance modify the underlying knowledge.
  • Versatility: ReadOnlySpan<T> can level to managed reminiscence, native reminiscence, or reminiscence managed on the stack, making it versatile for varied situations.

Contemplate a state of affairs the place it’s good to initialize a group effectively.

public void AddScores(params int[] scores)
    var scoresCollection = new int[] { 75, 88, 92 };

In C# 13, you possibly can obtain this with higher efficiency utilizing ReadOnlySpan<T>.

public void AddScores(ReadOnlySpan<int> scores)
    foreach (var rating in scores)
        // Course of scores with out allocations

That is helpful for apps that want optimum efficiency, corresponding to real-time methods, sport growth, and high-frequency buying and selling functions.

Help for IEnumerable<T>

The params key phrase has been enhanced to work with IEnumerable<T>, permitting you to go collections on to strategies that settle for a variable variety of arguments. This enhancement improves the pliability and usefulness of the params key phrase.

Seek advice from the next code instance.

utilizing System;
utilizing System.Collections.Generic;

public class Program
    public static void Essential()
        // Utilizing params with IEnumerable<T>.
        AddItems(new Checklist<int> { 1, 2, 3, 4, 5 });

    // Technique accepting params with IEnumerable<T>.
    public static void AddItems(params IEnumerable<int>[] collections)
        foreach (var assortment in collections)
            foreach (var merchandise in assortment)

Modernized thread synchronization with lock  

C# 13 introduces the System.Threading.Lock kind, designed to enhance thread synchronization practices. It boasts a superior API in comparison with the standard System.Threading.Monitor method.

Key options

  • Unique execution scope: The Lock.EnterScope() technique establishes an unique execution scope. This ensures that just one thread executes the code inside the scope at a time.
  • Eliminate sample: The returned ref struct from Lock.EnterScope() helps the Dispose() sample, permitting a swish exit from the scope. This ensures that the lock is launched even when an exception happens.
  • Integration with lock assertion: The C# lock assertion now acknowledges when the goal is a lock object and makes use of the up to date API. This integration simplifies the code and improves thread security.


  • Improved thread security: Through the use of the Lock kind, builders can obtain higher synchronization and keep away from frequent pitfalls related to thread competition.
  • Code maintainability: The brand new API makes the code extra readable and maintainable, lowering the complexity of thread synchronization.

Auto properties with customized logic

Auto properties have been a handy function since C# 3, however they’ve limitations. Particularly, including customized logic to the getters or setters required reverting to full property syntax, which meant extra boilerplate code. C# 13 introduces a big enhancement to auto-properties, which may now embrace customized logic immediately inside their getters and setters.
Let’s clarify this with the next code instance. Contemplate a state of affairs the place you wish to be sure that a date property is all the time set to the present date if the supplied worth is up to now.

utilizing System;

public class Occasion
    personal DateTime eventDate;

    public DateTime EventDate
        get => eventDate;
        set => eventDate = worth < DateTime.Now ? DateTime.Now : worth;

public class Program
    public static void Essential()
        Occasion myEvent = new Occasion();
        // Setting a previous date.
        myEvent.EventDate = new DateTime(2020, 1, 1);
        Console.WriteLine(myEvent.EventDate); // Outputs present date

        // Setting a future date.
        myEvent.EventDate = new DateTime(2025, 1, 1);
        Console.WriteLine(myEvent.EventDate); // Outputs 2025-01-01

With the auto property, you possibly can implement customized logic immediately inside the property definition, lowering the necessity for backing fields and retaining your code concise and readable.

New escape sequence for ESCAPE character

C# 13 introduces a extra handy solution to characterize the ESCAPE character (Unicode U+001B) inside character literals. This new function permits builders to make use of the e escape sequence as an alternative of the older strategies, u001B or x1B. This enhancement simplifies code readability and reduces potential errors related to hexadecimal interpretations.

Earlier than C# 13, representing the ESCAPE character required utilizing both the Unicode escape sequence u001B or the hexadecimal escape sequence x1B. These strategies might be much less readable and extra vulnerable to errors, particularly if the next characters have been legitimate hexadecimal digits.


char escapeChar1 = 'u001B'; // Utilizing Unicode escape sequence.
char escapeChar2 = 'x1B';   // Utilizing hexadecimal escape sequence.

With C# 13, now you can use the e escape sequence to characterize the ESCAPE character. This new technique is extra intuitive and reduces the chance of errors.

C# 13

char escapeChar="e"; // Utilizing the brand new escape sequence.


  • Improved readability: The e escape sequence is extra concise and simpler to learn in comparison with u001B or x1B.
  • Lowered errors: Utilizing e minimizes the danger of errors that may happen with hexadecimal interpretations, the place subsequent characters could be misinterpreted as a part of the escape sequence.
  • Consistency: The brand new escape sequence aligns with different frequent escape sequences, making the code extra constant and simpler to know.

Implicit index operator in object initializers

C# 13 permits utilizing the implicit “from the tip” index operator (^) inside object initializer expressions. This allows you to initialize arrays immediately from the tip, as showcased within the following instance.

var countdown = new TimerRemaining()
    buffer =
         = 0,
         = 1,
         = 2,
        // ... (continues to 9)

This code snippet initializes an array containing values from 9 all the way down to 0, attaining a countdown impact. Earlier than C# 13, initializing arrays from the tip inside object initializers wasn’t attainable.

Extension for every little thing: Strategies, properties, indexers, and static members

C# 13 expands the idea of extension strategies to a brand new degree by together with properties, indexers, and static strategies. This complete extension mechanism enhances code discoverability and usefulness, making it simpler for builders to increase current varieties with further performance with out modifying the supply code.

Extension strategies

Extension strategies have existed since C# 3. They permit us so as to add new strategies to current varieties with out altering their definitions. These strategies are outlined as static strategies in static courses, and the “this” key phrase specifies the kind they lengthen.

public static class StringExtensions
    public static bool IsNullOrEmpty(this string str)
        return string.IsNullOrEmpty(str);

Extension properties

C# 13 introduces extension properties, enabling builders so as to add new properties to current varieties. This enables for extra intuitive and readable code.

Within the following code instance, the Age property is outlined as an extension property for the DateTime kind. It calculates the age based mostly on the delivery date and the present date. The extension property is outlined inside a static class DateTimeExtensions. It is a requirement for extension strategies and properties.

public static class DateTimeExtensions
    public static int Age(this DateTime birthDate)
        var right this moment = DateTime.At the moment;
        int age = right this moment.12 months - birthDate.12 months;
        if (birthDate.Date > right this moment.AddYears(-age)) age--;
        return age;

The “this” key phrase earlier than the birthDate parameter signifies that the Age property is an extension property for the DateTime kind. This property calculates the age by subtracting the delivery 12 months from the present 12 months. It additionally adjusts the age if the delivery date is just not but within the present 12 months.

Extension indexers

With C# 13, now you can outline extension indexers, permitting you so as to add customized indexing habits to current varieties.

Within the following code instance, we’ve proven the best way to create an extension indexer for the Checklist<T> kind that retrieves parts from the tip of the checklist.

public static class ListExtensions
    public static T GetFromEnd<T>(this Checklist<T> checklist, int indexFromEnd)
        return checklist[list.Count - indexFromEnd - 1];

This extension indexer means that you can entry parts from the tip of the checklist utilizing a zero-based index, making it simpler to work with lists in reverse order. For instance, checklist.GetFromEnd(0) will return the final component, the checklist.GetFromEnd(1) will return the second-to-last component, and so forth.

Extension static members

C# 13 additionally helps extension static members, enabling the addition of static strategies to current varieties.

Within the following code instance, we’ve proven the best way to create an extension static technique for the double kind that calculates the sq. of a given worth.

public static class MathExtensions
    public static double Sq.(this double worth)
        return worth * worth;

This extension static technique means that you can name the Sq. technique immediately on a double worth, making the code extra intuitive and readable.


  • Enhanced code discoverability: By extending current varieties with further performance, builders could make their code extra discoverable and simpler to know.
  • Improved usability: Extension properties, indexers, and static members present a extra intuitive solution to work together with varieties, making the code readable and maintainable.
  • Separation of considerations: Extension members permit builders so as to add performance with out modifying the supply code, selling a cleaner separation of considerations.

Optimized technique group pure kind

C# 13 introduces an optimized method for technique group pure kind decision, refining the overload decision course of involving technique teams. This function enhances efficiency and aligns extra intently with the general overload decision algorithm.

In earlier variations of C#, when the compiler encountered a way group, it will generate a whole checklist of candidate strategies for that group. If a “pure kind” was required, it was decided based mostly on all the set of candidate strategies. This method might be inefficient, particularly when coping with giant units of strategies or complicated generic constraints.

C# 13 streamlines this course of by progressively eliminating inapplicable strategies at every scope. This consists of:

  • Scope-by-scope analysis: The compiler now considers candidate strategies scope-by-scope, beginning with occasion strategies and transferring to every subsequent scope of extension strategies.
  • Pruning inapplicable strategies: The compiler prunes strategies with no probability of succeeding early within the course of. This consists of:
    • Generic strategies with incorrect arity: The strategies shall be eradicated, in the event that they comprise a unique variety of kind arguments than the required.
    • Unhappy constraints: Generic strategies that don’t fulfill their constraints are additionally pruned.

By eliminating inapplicable strategies earlier, the compiler reduces the variety of candidate strategies that must be thought of, enhancing the effectivity of the overload decision course of.


Thanks for studying! C# 13 delivers compelling enhancements that empower builders to put in writing extra streamlined, strong, and expressive code. These options provide vital benefits for varied growth situations, from the flexibility of params collections to the improved lock object and the comfort of the brand new escape sequence.

It continues to evolve by refining current options and introducing new capabilities that improve productiveness and efficiency. We encourage you to discover and incorporate these new options into your C# tasks to raise your coding expertise. Let’s embrace these thrilling modifications and proceed to construct superb software program collectively. Completely happy coding!

The newest model of Important Studio—Syncfusion’s assortment of eighteen-hundred-plus UI elements and frameworks for cellular, net, and desktop growth—is obtainable for present clients from the License and Downloads web page. If you’re not a Syncfusion buyer, you can begin a 30-day free trial to attempt all of the elements at Syncfusion dot com slash downloads.

If in case you have questions, contact us via our help boardshelp portal, or suggestions portal at Syncfusion. We’re all the time pleased to help you!

Associated blogs



Please enter your comment!
Please enter your name here

Most Popular

Recent Comments