Using type aliases to make code clearer with generics

 
 
  • Gérald Barré

When you use generic types in C#, it is sometimes hard to understand what the generic argument can represent. For example, what do the strings represent in Dictionary<string, string>? To make the code clearer, you can use type aliases.

C#
// ❌ What does the string means?
_ = new Dictionary<string, string>();
C#
// Create aliases
using UserId = string;
using ProjectId = string;

// Use the type aliases
// ✅ It's clear that the first string is a UserId and the second string is a ProjectId
_ = new Dictionary<UserId, ProjectId>();

While type aliases are not a new feature in C#, they are not used as often as they could be. They can make the code clearer and easier to understand, especially when you use generic types.

However, the IDE is not very helpful when you use type aliases. For example, if you hover over a variable in the code above, the tooltip may not show the right alias. Visual Studio shows the first alias Dictionary<UserId, UserId>, and Rider doesn't use any alias Dictionary<string, string>. It would be nice if the IDE could show the original declaration.

Tooltip in Visual Studio

Tooltip in JetBrains Rider

Also, it's only an alias. You can assign a string to a UserId and vice versa. This is not a new type that you can use to enforce type safety. If you want type-safety for your aliases, you can use a library like Meziantou.Framework.StronglyTypedId. It also solves the IDE issue with tooltips.

C#
_ = new Dictionary<UserId, ProjectId>();

// Requires Meziantou.Framework.StronglyTypedId
// The Roslyn Source Generator generate the code of the class
[StronglyTypedId<string>]partial class UserId;
[StronglyTypedId<string>]partial class ProjectId;

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub