Microsoft announced last Tuesday (11/04) some features planned for C# 12, the new version of the language scheduled to be released together with .NET 8 at the end of 2023. More information can be found in an official post on the .NET platform blog:
https://devblogs.microsoft.com/dotnet/check-out-csharp-12-preview/
As I did in previous versions, with this new article, I start a series about new features that integrate C# 12. In this first post, I will demonstrate the possibility of using aliases (“nicknames”) for types, using the using directive for this.
It was necessary to enable support for resources in Preview mode in the .csproj file of the project I created for testing, making use of the LangVersion attribute in this case:
This example is also available on GitHub (based on .NET 8 Preview 3):
https://github.com/renatogroffe/CSharp12-AliasesTypes
If you find this useful, please give a ⭐️ to support. I also invite you to follow me on GitHub!
In the implementation of the static class Testes, I used 2 aliases:
-> ConversoesFahrenheit, an array of primitive type double declared through the using directive (line 1). This alias will be used in the signature of the ConverterTemperaturas method (line 9), which will display the results of converting various temperatures from Fahrenheit to Celsius and Kelvin scales;
-> CalculoIMC, which is nothing more than a tuple formed by the Peso and Altura properties (both of type double — line 2). The CalcularIMC method (line 23) uses this alias, calculating the BMI (Body Mass Index) and further determining the weight classification for a person.
https://gist.github.com/renatogroffe/24c1be163994c8698a400c2c56d866bd#file-testes-cs
IntelliSense itself in Visual Studio 2022 (I used version 17.6.0 Preview 3.0 here) will be able to predict the presence of aliases, displaying the types to which they refer as a hint. We can observe this with the ConverterTemperaturas method:
And also with calls to the CalcularIMC method:
In the next listing, we have the code for the Program.cs file, using the methods ConverterTemperaturas (receiving an array of type double) and CalcularIMC (5 calls receiving tuples as parameters) that were defined in the Testes class:
https://gist.github.com/renatogroffe/333dfddc8dc1cf4e22eacf346390e289#file-program-cs
The result of running this example application is shown in the following image:
If you, who are reading this, want to know more about other new features in .NET 8, here are links to articles I’ve already published about the new version planned for the .NET platform:
.NET 8: First tests with Preview 1 + JSON deserialization improvements
What’s New in .NET 8: Setting Possible Values with AllowedValuesAttribute
Leave a comment