Introduction

edit

Meziantou.Framework.StronglyTypedId is a C# source generator. You declare a partial struct or class with the [StronglyTypedId] attribute and the type of its value, and the generator writes the rest at compile time: the value, the factory method, equality, parsing, formatting and the converters that serializers and frameworks need.

[StronglyTypedId<int>]
public partial struct ProjectId { }

A method that takes a ProjectId cannot receive a CustomerId or a plain int by mistake: the compiler rejects it. The ID is still stored, serialized and bound as its underlying value: 42 in JSON, in a database column or in a URL.

What you can do with it

Principles

  • Everything happens at compile time. The generated code is plain C# in your assembly: no reflection, and no runtime dependency on the generator. The attributes are removed from the compiled assembly.
  • An ID is its value. Two IDs are equal when their values are equal, and every converter reads and writes the bare value, not an object that contains it.
  • Culture never changes the result. Parsing and formatting always use the invariant culture.
  • Your code wins. When you write a member that the generator would generate, such as the constructor or ToString, the generator uses yours instead.
  • Converters follow your references. A converter is generated only when the project can use it: the Newtonsoft.Json converter needs a reference to Newtonsoft.Json, the MongoDB serializer one to MongoDB.Bson, and the YAML and TOML converters one to Meziantou.Framework.Yaml and Meziantou.Framework.Toml.

Packages and namespaces

PackageContainsNamespace
Meziantou.Framework.StronglyTypedIdThe source generator, its analyzer and the attributesMeziantou.Framework.Annotations
Meziantou.Framework.StronglyTypedId.InterfacesIStronglyTypedId and IStronglyTypedId<T> (optional)Meziantou.Framework

Next steps