DEV Community

Cover image for Alias any Type with C# 12
Michael Jolley
Michael Jolley

Posted on • Originally published at baldbeardedbuilder.com

Alias any Type with C# 12

C# has had the ability to alias namespaces and named types for a long time. It's useful for avoiding naming conflicts between libaries or for using simpler names for complex generic types. If you're not familiar with namespace and type aliasing, here is an example:

// Namespace alias
using SuperJSON = System.Text.Json;
var document = SuperJSON.JsonSerializer.Serialize("{}");

// Type alias
using SuperJSON = System.Text.Json.JsonSerializer;
var document = SuperJSON.Serialize("{}");
Enter fullscreen mode Exit fullscreen mode

New Aliasable Types

With the release of C# 12, developers are gaining the ability to alias almost all types. Let's review some of the new options.

Aliasing Tuple Types

Tuples are commonly used as method return types, but when they're used multiple times, aliasing can help us keep our code cleaner and more legible.

using Country = (string Abbreviation, string Name, double GDPPerCapita);

Country GetCountry(string abbreviation)
{
    // Logic here
    return ("US", "United States of America", 63529);
}

List<Country> GetCountries()
{
    // Logic here
    return [("US", "United States of America", 63529)];
}

Console.WriteLine(GetCountry("US").Name);
Enter fullscreen mode Exit fullscreen mode

Aliasing Types with Pointers

Most of time, C# developers don't need access to pointers, but now you can alias them when you do.

using bytePtr = byte*;

unsafe void MyMethod()
{
    int x = 1024;
    bytePtr ptr = (byte*)&x;

    Console.Write("The 4 bytes of the integer:");

    for (int i = 0 ; i < sizeof(int) ; ++i)
    {
        Console.Write(" {0:X2}", *ptr);
        ptr++;
    }

    Console.WriteLine();
    Console.WriteLine("The value of the integer: {0}", x);
}
Enter fullscreen mode Exit fullscreen mode

Aliasing Array Types

Aliased array types are another addition in C# 12, which should make your declarations cleaner and more legible for teams.

using Companies = System.Collections.Generic.List<Company>;

Companies GetCompanies()
{
    return [
        new Company() { Id = 1, Name = "Acme Co."}
    ];
}

class Company
{
    public string Name;
    public int Id;
}
Enter fullscreen mode Exit fullscreen mode

Aliasing Nullable Types

Most types are available for aliasing in C# 12, including nullable value types. However, nullable reference types aren't available for aliasing.

Conclusion

Expanded capabilities for aliasing in C# 12 has the potential to make your code cleaner and more readable for your teams.

Top comments (0)