.NET 8 and C# 12 — Alias any type

Henrique Siebert Domareski
2 min readNov 21, 2023

--

.NET 8 brings a lot of performance improvements and also includes a series of new features with C# 12. In this article, I present the Alias any type feature.

In previous versions of C#, it was already possible to use aliases for the built-in types, for example:

using MyConsole = System.Console;

MyConsole.WriteLine("Test console");

But now with this new feature, it’s also possible to define aliases for tuples, arrays, pointers and other potentially unsafe types (except nullable reference types).

For demonstration purposes, I created a console application with .NET 8, and I configured the LangVersion in the .csproj file with the preview value:

<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<LangVersion>preview</LangVersion>
</PropertyGroup>

</Project>

The alias should also be declared in the using section of your class. This is an example of how you can declare and initialise a tuple with alias:

// Declaring:
using Person = (string name, int age, string country);

// Initialising:
Person person = new ("Aragorn", 33, "Netherlands");

Console.WriteLine(person);

// Output:
(Aragorn, 33, Netherlands)

You can also use the alias as a parameter in a method:

public static void PrintPerson(Person person)
{
Console.WriteLine($"{person.name}, {person.age}, {person.country}");
}

// Output:
Aragorn, 33, Netherlands

Conclusion

This new feature of C# 12 allows you to make use of aliases with different object types, making your code cleaner and easier to read.

This is the link for the project in GitHub: https://github.com/henriquesd/DotNet8Examples

If you like this demo, I kindly ask you to give a ⭐️ in the repository.

Thanks for reading!

--

--