C# 12 Simplifies Syntax |
Written by Kay Ewbank |
Monday, 18 December 2023 |
C# 12 was released as part of .NET 8. The main work on C# has been simplification of the syntax and making code execution faster. The syntax simplification features in C# 12 include collection expressions, primary constructors for all classes and structs, syntax to alias any type, and the default parameters for lambda expressions. Collection expresions simplify the need in earlier verisons of C# to use different syntax for different scenarios when creating a collection. Instead, collection expressions provide a unified syntax that the compiler can use to create fast code, and in many cases, the compiler will also set the collection capacity and avoid copying data. Developers can also use a new spread operator to include the elements of one or more collections or enumerable expressions within a collection expression. C# 12 also extends primary constructors to work on all classes and structs, rather than just records. Primary constructors let you define constructor parameters when you declare the class. You can now add primary constructors to any type. A related improvement is the ability to use more types when setting up alias directives. Aliasing types is a straightforward way to remove complex type signatures from your code. Support has also been added in this release for declaring default parameters in lambda expressions. These let calling code skip passing values and provide a way to add parameters to existing lambda expressions without breaking calling code. The C# team says this simplifies accessing lambda expressions in the same way default parameters in methods simplify calling methods. In terms of performance improvements, this version sees support added for ref readonly parameters and inline arrays. The C# team says the addition of ref readonly parameters provides the final combination of passing parameters by reference or by value. This enables more clarity for APIs that might be using ref parameters or in parameters. Inline arrays (struct-based, fixed length array types) provide a safe way to work with memory buffers. If you want to manipulate a block of memory in earlier releases, the choices were to use stackalloc storage or pointers, but those techniques required that your assembly enable unsafe code. Inline array types represent a fixed size array, can be used in safe code, and so improve your app's performance when manipulating buffers. C# is part of the .NET SDK. More InformationRelated ArticlesC#11 Will Support Raw String Literals C# Guru - An Interview With Eric Lippert To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.
Comments
or email your comment to: comments@i-programmer.info
|