The most interesting 4 new features of C# 13
Intro
C# 13 was released alongside .NET and it brings several new features aimed to simplify complex coding scenarios, improve performance, and enhance code clarity.
Whether you’re working on multi-threaded applications, high-performance computing, or modern asynchronous programming, C# 13 has some new tips to help you write cleaner and more maintainable code.
This article highlights the most exciting new features of C# 13 and I’ll try to explain their impact in real-world development.
Let’s start
- Scoped Locks for Thread Safety — C# 13 introduces a new type of thread synchronization System.Threading.Lock, which simplifies managing critical sections in multi-threaded code.
Lock myLock = new Lock();
using (myLock.EnterScope())
{
// Critical section - thread-safe execution
Console.WriteLine("Thread-safe operation.");
}
The “using” statement automatically releases the lock and let’s be honest, it is a reduced boilerplate code for acquiring and releasing locks, compared with the mambo jumbo you needed you do in older versions.
2. Params Collections — If you remember, this could be used only for array types. Well, now you don’t have this limitation and you have access to multiple types (I don’t really see the point in enumerating them here)
void Process(params ReadOnlySpan<int> numbers)
{
foreach (var number in numbers)
Console.WriteLine(number);
}
Process(stackalloc[] { 1, 2, 3 }); // Stack allocated collection
Benefits:
- As you can see, it’s easy for stack-allocated data to be passed efficiently.
- Is as flexible as you need it gets. You can combine stack-allocated spans with other types like arrays or strings in the same param argument.
3. Partial Properties and Indexers — Basically you can have the declaration and implementation split across different files. This improves modularity in large codebases.
//File 1
partial class Configuration
{
public partial string ConnectionString { get; set; }
}
//File 2
partial class Configuration
{
private string connection;
public partial string ConnectionString
{
get => connection ?? "DefaultConnection";
set => connection = value;
}
}
In theory, you can view this improving readability by separating contract from implementation, as you do with interfaces and implementations. It is also nice because you get more extensibility on what you can do from the organizing your code point of view.
As a personal preference, I won’t use this so much, because I don’t like partial in general.
4. Escape Sequence for ASCII Escape Character — A new \e escape sequence simplifies using the ASCII escape character
Conclusion
Most likely, other features might seem more interesting to you, but for me, those 4 are the nicest. You can find the entire list with what’s new in 13 here and the breaking changes from 12, here.