.NET 8 brought a set of new language features with the introduction of C# 12, check this article to learn about the top 5 Features added to the amazing language of C#
You can start using these features right away, just make sure to update your IDE to the latest version, and specifically if you are using Visual Studio 2022, either update to the latest version or make sure your version is 17.9 or above.
P.S. The announcement of C# 13 with .NET 9 is coming up on 12-14, November, 2024 during the biggest online .NET Conference – Dotnet Conf 2024
Stay tuned for my next posts, I’ll prepare another blog issue to highlight the key language features added in C# 13
So let’s get started with the Top 5 Language Features in C# 12
Top 5 Language Features in C# 12
1. Primary Constructors
A primary constructor is a concise way to write parametrized constructor
This constructor’s parameters have class or struct level scope
If the primary constructor’s parameters are accessed in a method within the class/struct, the compiler creates hidden fields to represent each parameter
You can use them to do different operations:
- Initialize Properties or Fields
- Initialize base class
- Specify Parameters in Dependency Injection
Useful with ASP.NET Core Controllers when you are injecting dependencies in controllers or services
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public class PostModel ( int id, string? title, string? description, bool isActive, DateTime? postedOn ) { public int Id => id; public string? Title => title; public string? Description => description; public bool isActive => isActive; public DateTime? PostedOn => postedOn; } |
2. Collection Expressions
It is a great feature to initialize collections using a simple and concise syntax
Collection expressions can be applied to Arrays, Lists and Spans
To create an empty collection, just do this:
1 |
List<string> emptyList = []; |
You can also use the 𝘀𝗽𝗿𝗲𝗮𝗱 𝗼𝗽𝗲𝗿𝗮𝘁𝗼𝗿 (or element) ..
It will combine multiple collections and return it into a single collection.
1 2 3 4 5 6 7 8 9 |
List<string> composers = ["Bach", "Purcell", "Vivaldi"]; List<string> composers2 = ["Monterverdi", "Corelli", "Albinoni"]; List<string> composersCombined = [.. composers, .. composers2]; Console.WriteLine(string.Join(",", composersCombined)); // Output: // Bach, Purcell, Vivaldi, Monterverdi, Corelli, Albinoni |
3. Alias Any Type
Now you can apply alias for any type by the ‘using’ keyword or (directive)
Previously you could only define alias for namespaces or named types
But with C# 12 you can now alias other types like tuples, arrays, dictionaries and others
It allows you to give a logical naming for it instead of using it as-is
The benefit of aliasing any types is that it can simplify how you create and initialize objects from complex types.
Also this feature can help in avoiding conflicts with external dependencies when using the type without providing a fully qualified name.
1 2 3 4 5 6 7 8 9 10 11 |
using BloodPressure = (int, int); BloodPressure normalBP = new(120, 80); Console.WriteLine( $""" The normal blood pressure is: {normalBP.Item1}/{normalBP.Item2} """); // Output: The normal blood pressure is: // 120/80 |
4. Default Lambda Parameters
Generally, the default parameters is not a new feature in C#
You have most likely used it at least in one or more of your projects, where you had to set a default parameter in your method.
Now in C# 12, the default parameters feature has been enabled for lambdas, so you could the benefit of default params while working with lambdas.
Default params for lambdas help in:
- Reducing boilerplate code to do null checks and provide a default value
- Avoiding the need to provide overloaded methods
- Better readability with default values being visible directly from the lambda signature
1 2 3 4 5 |
var postLambda = (string category, string title = "Untitled") => $"Post title is {title}"; Console.WriteLine(postLambda(".NET")); |
A good example is a minimal API use case, where you can have a flexible API with lambda that takes defines default values in case they were not provided by the client.
1 2 3 4 |
app.MapGet("/posts", async (PostService postService, int index = 0, int pageSize = 10) => { return await postService.GetPostsAsync(index, pageSize); }); |
5. Inline Arrays
This is a feature introduced with .NET 8, where you can define a fixed-size array for a struct type at compile time.
A new attribute has been introduced:
[System.Runtime.CompilerServices.InlineArray(FixedArraySize)]
The new attribute can be applied to struct types.
This brings in a memory optimization benefit that the array will be created (allocated) in the stack.
Note that both Span and ReadOnlySpan are built-in types that use a similar storage structure (stack) as inline arrays in the background.
However, the Span types are more flexible features to work with slices of arrays.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
var top5Posts = new FeaturedArray<string>(); top5Posts[0] = ".NET 8"; top5Posts[1] = "C# 12"; top5Posts[2] = "ASP.NET Core 8"; top5Posts[3] = "EF Core 8"; top5Posts[4] = "Blazor"; StringBuilder sb = new(); foreach (var post in top5Posts) { sb.Append($"{post}, "); } var finalOutout = sb.ToString().Trim().Remove(sb.Length - 2, 1); Console.WriteLine(finalOutout); [InlineArray(5)] public struct FeaturedArray<T> { private T _title; } // Output: // .NET 8, C# 12, ASP.NET Core 8, EF Core 8, Blazor |
Summary
These have been the key features introduced in C# 12 bundled with .NET 8
So which of these features have you been using in your recent .NET 8 projects?
Let us know in the comments section your experience with .NET 8 and C# 12.
Also make sure to share this with your network.
Join 33K+ amazing followers on my LinkedIn to get the latest tips in .NET and C#
References
What’s new in C# 12
https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-12
Take a look on what’s new for .NET 8, which includes these amazing changes as part of C# 12
https://learn.microsoft.com/en-us/dotnet/core/whats-new/dotnet-8/overview
Collaboration
I am always open to discuss any protentional opportunities and collaborations.
Check this page to learn more about how we can benefit each other.
Sponsorships and Collaborations
Bonus
Enjoy the fine and peaceful tunes of Mozart with this amazing violin concert.
Mozart Concerto n. 4 in D major KV 218 | Kevin Zhu – Queen Elisabeth Competition 2024