Type Aliases - Making Code Clearer with Generics
Type Aliases - Making Code Clearer with Generics
When working with generic collections, we often encounter code that’s not immediately clear about its purpose. For example:
1
// ❌ What does the string means? = new Dictionary<string, string>();
The problem here is that we don’t know what those strings means, what it represents. This problem is called primitive obsession, more can be read here: Primitive Obsession
To solve it we can use aliases:
1
2
3
4
5
// 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>();
Alternative option is using records:
1
2
3
4
5
// Create records
public record UserId(string id);
public record ProjectId(string id);
// 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>();
Source
For more details about type aliases, check out the original article by Gérald Barré.
This post is licensed under CC BY 4.0 by the author.