-
C# 12 features: Default lambda parameters
Part 4 in a series on new language features in C# 12.
Default lambda parameters
A pretty simple addition to the language - you can now provide default values for lambda expression parameters.
var IncrementBy = (int source, int increment = 1) => source + increment;
In the lambda defined above, if you don't supply the
increment
parameter, it defaults to1
.Again, interesting, but I've not come across a need to use this yet.
Further reading
Example source
https://github.com/flcdrg/csharp-12/blob/main/04-optional-params-lambda/LambdaParameters.cs
-
C# 12 features: ref readonly
Part 3 in a series on new language features in C# 12.
ref readonly
modifierA bit more of a niche feature - if you have code that is passing structs by
ref
, but you don't need to (or want to) allow modification of the parameter, you can now indicate it is readonly.public static void ByRefReadonly(ref readonly Point p) { //p = new Point(2, 3); Console.WriteLine(p); }
In the code sample above,
Point
is a struct or record type. If you uncommented the line then the compiler will emit an error.Interesting, but I've not come across a need to use this yet.
Further reading
Example source
https://github.com/flcdrg/csharp-12/blob/main/02-collection-expressions/CollectionExpressions.cs
-
C# 12 features: Collection expressions
Part 2 in a series on new language features in C# 12.
Collection expressions
You can now use square brackets
[]
to initialise a collection! Usually square brackets indicate an array, but the collection expression can be assigned to other collection types too.You can use them to assign values to fields or in method bodies.
private List<int> numbersList = [1, 2, 3, 4, 5];
Like primary constructors, I've also found these quite useful in new .NET 8 projects.
Further reading
Example source
https://github.com/flcdrg/csharp-12/blob/main/02-collection-expressions/CollectionExpressions.cs