Introduction

Ever encountered a method like this?

public int Process(int userId, int itemId, int categoryId) {...}

What does this method return? Is the int a count of items processed or an order ID? This ambiguity can lead to confusion and errors.

The Problem with Primitive Types

Using primitive types like int for the IDs in your C# classes is common, but it can be risky. When multiple IDs are represented by the same type, it’s easy to mix them up. This can lead to bugs that burn hours of debugging time and can slip into production undetected.

Consider the following scenario:

int userId = 5;
int itemId = 8;
int categoryId = 13;
int orderId = processor.Process(itemId, categoryId, userId);

This code compiles but is wrong. It introduces a sneaky bug that could take hours to resolve. The parameters are swapped, leading to incorrect processing.

The Solution: Strongly Typed IDs

To avoid such issues, we can use Strongly Typed IDs. By creating distinct types for each ID, we make our code more readable and less error-prone.

Here’s how it looks:

public OrderId Process(UserId userId, ItemId itemId, CategoryId categoryId)
{...}

Now, there’s no mistaking what this method accepts and returns. If you accidentally swap the order of your arguments like in the previous example:

UserId userId = 5;
ItemId itemId = 8;
CategoryId categoryId = 13;
OrderId orderId = processor.Process(itemId, categoryId, userId);

your code won’t compile!

Benefits of Strongly Typed IDs

  1. Compile-Time Safety: Catches errors at compile time, reducing runtime bugs.
  2. Improved Readability: Makes code self-documenting and easier to understand.
  3. Reduced Risk of Errors: Prevents type mismatches, minimizing the risk of bugs.

Implementing Strongly Typed IDs

In our greenfield projects, we leverage Andrew Lock’s StronglyTypedIds library for C#. This library provides a proven, Roslyn-powered generator used by thousands of developers for creating strongly-typed IDs, making it easier to implement and manage them in your codebase.

Conclusion

Strongly Typed IDs are a simple yet powerful tool to improve code quality. By adopting this approach, you can craft systems that are more reliable and easier to maintain. Embrace Strongly Typed IDs and build better systems so you can build better business.

If you’re looking to implement these kinds of robust coding practices in your next project, our custom software development team specializes in building maintainable, type-safe applications using modern C# development techniques.