As every year on the blog, we analyze the new features of our favorite programming language, in this case C#.
Before we start, remember that .NET 11, as well as C#, is a short-term support version (https://www.netmentor.es/entrada/explicacion-versiones-dotnet), which means that many of you are not going to use these features because of the policies your company has.
Table of contents
1 - Union types
We start with the big one. If you have been in C# for years, you know that discriminated unions are the most requested feature in the history of the language. In last year's post I told you that Microsoft had postponed it to C# 16 or 17, well, they have moved ahead and in C# 15 we have the first version.
A union type represents a value that can be one of several types, and it is declared with the new union keyword:
public record class Cat(string Name);
public record class Dog(string Name);
public record class Bird(string Name);
public union Pet(Cat, Dog, Bird);
From there you have implicit conversions from each of the types, and most importantly, the compiler knows all the types and is able to identify them, for example a switch can be the following:
Pet pet = new Dog("Pablo");
string name = pet switch
{
Dog d => d.Name,
Cat c => c.Name,
Bird b => b.Name,
};
As a side effect, it can make the result pattern possible to implement natively instead of having to use third-party libraries.
If you want to see more details, we covered a full blog post and you have the analysis at the following link: https://www.netmentor.es/entrada/union-types-net-11-preview
2 - The closed keyword
A new keyword arrives in the language, closed, which, when applied to a class, indicates that it can only be inherited from within the same assembly.
For example, the following code uses the closed keyword in the class declaration:
public closed record class GateState;
public record class Closed : GateState;
public record class Open(int Percent) : GateState;
to give an example with pattern matching, the compiler is able to identify what type it is:
internal class ClosedHierarchies
{
public void Example()
{
GateState state = new Open(20);
string description = Describe(state);
Console.WriteLine(description);
}
string Describe(GateState state) => state switch
{
Closed => "closed",
Open(var percent) => $"{percent}% open",
};
}
In any case, the behavior of the new keyword is equivalent to sealed class in Kotlin or Scala, be careful, not the same value as in C#, sealed in C# means that we cannot inherit from that class but it is a "normal" class.
When we use closed, the behavior changes. First of all, it is implicitly abstract and it cannot be changed with sealed, static, or with explicit abstract.
And then it is not transitive, which means that if a class inherits from a closed class in the same assembly and, in turn, another class inherits from this new class, another one can inherit from it from outside the assembly.
3 - Arguments in collection expressions
With the arrival of C# 12 we got collection expressions, the new syntax for initializing collections. What we could not do was pass arguments to the collection constructor, for example the initial capacity or the comparer.
In C# 15, the with() element is added, which lets us pass arguments to the constructor or to the collection factory method.
string[] values = ["one", "two", "three"];
// Capacity on names
List<string> names = [with(capacity: values.Length * 2), .. values];
Console.WriteLine(string.Join(", ", names));
// Comparer para HashSet<T>
HashSet<string> set = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "Hello", "HELLO", "hello" };
Console.WriteLine(string.Join(", ", set));
4 - Extension indexer
Last year we saw extension members, the new syntax with the extension keyword that lets you extend a type with methods and properties. What was left out in C# 14 were indexers, and in C# 15 we already have them.
Since an indexer is always an instance member, the extension block needs a named receiver:
public static class SequenceIndexer
{
extension(IEnumerable<int> sequence)
{
public int this[int index] => sequence.ElementAt(index);
}
}
And you use it as if the indexer were part of the type itself:
internal class ExtensionIndexers
{
public void Example()
{
IEnumerable<int> numbers = [1, 2, 3, 4, 5];
Console.WriteLine(numbers[2]);
}
}
With this, extension members already cover practically everything a type can have: methods, properties, indexers, and static members. If you have not started using the new syntax in new code yet, this is a good moment.
5 - Break and continue with labels
We have all written a loop inside another loop at some point and needed to exit the outer one from the inner one. The options until now were a boolean variable that you check at each level, or a goto, and we already know what everyone thinks about that.
In C# 15, break and continue can indicate a label of the loop (or switch) they affect:
internal class BreakContinue
{
public void Example()
{
int[,] grid =
{
{ 1, 2, 3 },
{ 4, -1, 6 },
{ 7, 8, 9 },
};
outer: for (int row = 0; row < grid.GetLength(0); row++)
{
for (int column = 0; column < grid.GetLength(1); column++)
{
if (grid[row, column] == -1)
{
continue outer;
}
if (grid[row, column] == 9)
{
Console.WriteLine($"Encontrado en [{row}, {column}]");
break outer;
}
}
}
}
The label goes directly on the loop, and if you do not indicate any, break and continue work exactly the same as always, on the innermost loop. Java and Go have had this for decades, so it is not like C# has invented anything, but it is appreciated.
6 - Memory changes
This is the most low-level change and, if you do not work with pointers, it probably will not affect you. But it is the beginning of a multi-version effort to redefine what memory safety means in C#.
The idea is for the unsafe context to stop being tied to the existence of a pointer and instead become tied to the operations that access unmanaged memory, which is where the real security problems are.
The first step is pointer relaxations. Compiling with LangVersion in preview, these operations no longer need unsafe:
Declaring a pointer and getting the address of a variable with &.
The fixed statement.
Converting a stackalloc to a pointer.
sizeof on any unmanaged type.
public void Example()
{
int number = 42;
int* pointer = &number;
int[] numbers = [10, 20, 30];
fixed (int* first = numbers)
{
// eliminar la referenica del puntero sigue requiriendo unsafe
}
}
All of this is in preview and needs AllowUnsafeBlocks, you have the details in the official documentation.
7 - Features that are not in C# 15
As every year, we are going to see what has been left at the door, everything is documented in the working set on GitHub, and most of it looks like it will go into C# 16. Even so, there is nothing you would say is super exciting, well, maybe runtime async, which we made a post about on the channel https://www.netmentor.es/entrada/runtime-async-net11 .
Aside from that, I like the proposal for dictionary expressions, to be able to initialize a dictionary with the syntax [“key”:value] similar to what other collections can already do in C#.
And finally, one that I find curious is chained comparisons. Imagine a situation where we have x > y && y > z, what chained comparisons are looking for is to be able to do x > y > z.
And well, that has been everything in this post, I hope you liked it!
Comments