Skip to content
  • English Deutsch

benjamin-abt.com

Performance is a feature | Cloud - AI - Azure - .NET - Sustainability

  • Home
  • Blog
  • Portfolio
    • Overview
    • Workshops & Training
    • Publications
  • Contact
  • Home
  • Blog

Better Code with custom Strong-Id Types

Better Code with custom Strong-Id Types
June 20, 2023 3 min read BEN ABT
.NET Csharp EF Core

This article was written in 2023. Versions, tools and recommendations may have changed since then. Newer posts are collected under .NET.

In many software architectures the problem exists that there are methods, which are specified a multiplicity of type-same parameters, whose meaning is however fundamentally different. In principle, this includes all handling of Ids or other essential values that have a logical meaning.

For example, we have a large number of IDs, which in this case have the same type, but have a completely different meaning.

C#
public Task Add(int userId, int newsId)

The risk now is that the developer mixes up the order of the parameters, this leads to logic as well as data problems - and this is not immediately obvious. There is no compiler error. In the end, this potential swapping of values can only be covered by unit tests.

The solution: Strong-IDs.

Strong IDs are achieved by defining custom types that replace the default types in their usage, but under the hood is still the previous data type; here a Guid. The implementation corresponds to the wrapper pattern.

C#
public Task Add(PlatformUserId userId, NewsId newsId)

If the developer swaps the parameters, there is a compiler error. This not only reduces the test effort, but also increases the software quality.

C# Limitations

In many languages there are built-in features in the form of alias support. For example, F# knows Type Abbreviations which gives me compiler-side support for type aliases without having to write my own wrappers - including errors in case of incorrect usage.

C# does not have such a feature. You have to write your own wrappers by force - unfortunately.

The wrapper implementation

There are several ways to implement such a String-ID class as a wrapper; however, the possibilities of C# 10 ease the effort a bit.

As a basis I create an interface and an abstract class, so that I have certain advantages in the use of generic methods and on the other hand I can use inheritance to have as little effort as possible in the implementation. Here as an example on the basis of an Int implementation.

C#
 1using System;
 2
 3namespace MyCSharp.Models;
 4
 5/// <summary>
 6/// Interface for integer-based strong IDs on the platform.
 7/// </summary>
 8/// <typeparam name="T">The type of the implementing ID.</typeparam>
 9public interface IPlatformIntegerStrongId<T> : IComparable<T>
10{
11    /// <summary>
12    /// Gets the integer value of the ID.
13    /// </summary>
14    int Value { get; }
15}
16
17/// <summary>
18/// Abstract class for integer-based strong IDs on the platform.
19/// </summary>
20/// <typeparam name="T">The type of the implementing ID.</typeparam>
21public abstract record class PlatformIntegerStrongId<T>(int Value)
22    : IPlatformIntegerStrongId<T> where T : IPlatformIntegerStrongId<T>
23{
24    /// <inheritdoc/>
25    public int CompareTo(T? other) => Value.CompareTo(other?.Value);
26
27    /// <inheritdoc/>
28    public sealed override string ToString() => Value.ToString();
29}

The implementation of my specific Strong ID class can now inherit from PlatformIntegerStrongId.

C#
1/// <summary>
2/// Represents a strong ID for a news item.
3/// </summary>
4public sealed record class NewsId(int Value)
5    : PlatformIntegerStrongId<NewsId>(Value)
6{ }

I have all my strong-ids currently defined as class, as struct has some limitations, including e.g. model binding in ASP.NET Core, some hurdles with json converters etc.

The usage

I can now use my Strong Id class - here now NewsId - in the method and have compiler support in case I swap parameters.

C#
public Task Add(PlatformUserId userId, NewsId newsId)

Conclusion

Strong Ids are not quite as easy and efficient to implement in C# as they are in F#. However, they bring enormous advantages during development, are widely usable and prevent problems very simply.

Related articles

Advanced Usage of MSSQL Indexed Views in EF Core

Jan 13, 2025 - 5 min read

Advanced Usage of MSSQL Indexed Views in EF Core

In the world of Microsoft SQL Server , views are a powerful tool for simplifying complex data queries. Simple views offer no real …

Increase Command Timeout for EF Core Migration Bundles

Jan 3, 2025 - 2 min read

Increase Command Timeout for EF Core Migration Bundles

EF Core Migration Bundles are standalone executable files that contain one or more Entity Framework Core migrations and can be applied …

New Data Annotation attributes with .NET 8

Nov 19, 2023 - 2 min read

New Data Annotation attributes with .NET 8

With .NET 8, the System.ComponentModel.DataAnnotations Namespace has been revised and some new attributes have been added that have been …


BEN ABT

BEN ABT

Ben is Chief Engineering Officer and Principal Software Engineer at Medialesson.de, with a strong focus on .NET and Microsoft Azure. In his professional role, he designs and builds highly scalable platforms for hybrid and cloud-based scenarios. He also advises companies and C-levels on migrating to the sovereign cloud.

He runs myCSharp.de, the largest and most active German-speaking C# community forum, actively contributes to both his own and external open-source projects and regularly shares his knowledge through his blog, at community events, conferences and as a writer for technical magazines.

Let's Work Together

Looking for an experienced Platform Architect or Engineer for your next project? Whether it's cloud migration, platform modernization or building new solutions from scratch - I'm here to help you succeed.

New Platforms

Modernization

Training & Consulting

Contact Me
X Facebook LinkedIn WhatsApp
Back Next Blog Post

Open for work!

Contact Me
BEN ABT BEN ABT Software Engineer · Microsoft MVP Passionate about .NET, Azure, performance optimization and sustainable software engineering.

Medialesson GmbH Logo

Microsoft MVP Logo

Recent posts

View all
Stop Using nginx as Your Default Static File Server in Docker

Stop Using nginx as Your Default Static File Server in …

Oct 24, 2026
Containerizing .NET in 2026 Without a Dockerfile

Containerizing .NET in 2026 Without a Dockerfile

Oct 20, 2026
Problem Details in ASP.NET Core and .NET 11

Problem Details in ASP.NET Core and .NET 11

Oct 5, 2026
Resilience in .NET with Microsoft.Extensions.Resilience

Resilience in .NET with Microsoft.Extensions.Resilience

Sep 21, 2026
What Matters in ASP.NET Core 11

What Matters in ASP.NET Core 11

Sep 14, 2026

Tags

.NET (192) Csharp (96) ASP.NET Core (48) Azure (41) DevOps (17) Docker (14) Microsoft (14) EF Core (11) Microsoft MVP (11) AI (10) GitHub (10) GitHub Copilot (10) ASP.NET (9) Security (9) Synology (9) Architecture (8) Raspberry (8) Azure Functions (7) Cloudflare (7) Bicep (6)
benjamin-abt.com

About BEN

Benjamin Abt is a Software Engineer, Platform Architect and Microsoft MVP specializing in .NET, Azure, cloud architecture, performance optimization and sustainable software development.

Connect

  • Follow me on GitHub
  • Follow me on LinkedIn
  • Follow me on Mastodon
  • Microsoft MVP profile
  • Follow SchwabenCode on GitHub
  • Follow me on X

Quick Links

  • Portfolio
  • Blog
  • Workshops & Training
  • Publications
  • Get in Touch
  • Sitemap
Open for Work

© Copyright Benjamin Abt & SchwabenCode | 2011 - 2026

Content licensed under CC BY 4.0 unless otherwise noted.

  • Impressum
  • Privacy
  • Contact