Skip to main content

Source Generator to generate strongly-typed id with all needed helpers such as converters for System.Text.Json, Newtonsoft.Json, MongoDB, YAML, or TOML.

Total Downloads
220.3K
220,280
Published
Nov 13, 2026
4d ago

Get Started

dotnet add package Meziantou.Framework.StronglyTypedId --version 3.0.10
ProductVersions
.NET
net10.0net11.0
.NET Standard
netstandard2.0

README

Meziantou.Framework.StronglyTypedId

The source generator generates constructors, properties, equality members, common interfaces, converters for multiple serializers. The attributes are in the Meziantou.Framework.Annotations namespace.

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

or using typeof if you're not using a version of C# that supports generic attributes

[StronglyTypedId(typeof(int))]
public partial struct CustomerId { }

StronglyTypedId generates the following code:

[System.ComponentModel.TypeConverterAttribute(typeof(ProjectIdTypeConverter))]
[System.Text.Json.Serialization.JsonConverterAttribute(typeof(ProjectIdJsonConverter))]
[Newtonsoft.Json.JsonConverterAttribute(typeof(ProjectIdNewtonsoftJsonConverter))]
[MongoDB.Bson.Serialization.Attributes.BsonSerializerAttribute(typeof(ProjectIdBsonConverter))]
public partial struct ProjectId :
    System.IEquatable<ProjectId>,
    System.IParsable<ProjectId>,         // .NET 7+
    System.ISpanParsable<ProjectId>,     // .NET 7+
    System.IUtf8SpanParsable<ProjectId>, // .NET 8+
    System.IFormattable,
    System.ISpanFormattable,             // .NET 6+
    System.IUtf8SpanFormattable,         // .NET 8+
    IStronglyTypedId,                    // When Meziantou.Framework.StronglyTypedId.Interfaces is referenced
    IStronglyTypedId<int>,               // When Meziantou.Framework.StronglyTypedId.Interfaces is referenced
    IComparable, IComparable<ProjectId>  // When at least one of the interface is explicitly defined by the user
{
    public int Value { get; }
    public string ValueAsString { get; } // Value formatted using InvariantCulture

    private ProjectId(int value);

    public static ProjectId FromInt32(int value);
    public static ProjectId Parse(string value);
    public static ProjectId Parse(ReadOnlySpan<char> value);
    public static bool TryParse(string value, out ProjectId result);
    public static bool TryParse(ReadOnlySpan<char> value, out ProjectId result);
    public override int GetHashCode();
    public override bool Equals(object? other);
    public bool Equals(ProjectId other);
    public static bool operator ==(ProjectId a, ProjectId b);
    public static bool operator !=(ProjectId a, ProjectId b);
    public override string ToString();

    public partial class ProjectIdTypeConverter : System.ComponentModel.TypeConverter
    {
        public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type sourceType);
        public override object? ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value);
        public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType);
        public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType);
    }

    // Generated only when System.Text.Json is accessible
    public partial class ProjectIdJsonConverter : System.Text.Json.Serialization.JsonConverter<ProjectId>
    {
        public override void Write(System.Text.Json.Utf8JsonWriter writer, ProjectId value, System.Text.Json.JsonSerializerOptions options);
        public override ProjectId Read(ref System.Text.Json.Utf8JsonReader reader, System.Type typeToConvert, System.Text.Json.JsonSerializerOptions options);
    }

    // Generated only when Newtonsoft.Json is accessible
    public partial class ProjectIdNewtonsoftJsonConverter : Newtonsoft.Json.JsonConverter
    {
        public override bool CanRead { get; }
        public override bool CanWrite { get; }
        public override bool CanConvert(System.Type type);
        public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object? value, Newtonsoft.Json.JsonSerializer serializer);
        public override object ReadJson(Newtonsoft.Json.JsonReader reader, System.Type objectType, object? existingValue, Newtonsoft.Json.JsonSerializer serializer);
    }

    // Generated only when MongoDB.Bson.Serialization.Serializers.SerializerBase is accessible
    public partial class ProjectIdBsonConverter : MongoDB.Bson.Serialization.Serializers.SerializerBase<ProjectId>
    {
        public override ProjectId Deserialize(MongoDB.Bson.Serialization.BsonDeserializationContext context, MongoDB.Bson.Serialization.BsonDeserializationArgs args);
        public override void Serialize(MongoDB.Bson.Serialization.BsonSerializationContext context, MongoDB.Bson.Serialization.BsonSerializationArgs args, ProjectId value);
    }
}

When the project references Meziantou.Framework.Yaml or Meziantou.Framework.Toml, the ID also gets a ProjectIdYamlConverter or a ProjectIdTomlConverter, registered with [YamlConverter] or [TomlConverter]. They write the value of the ID:

public sealed record OrderLine(ProductId ProductId, ProjectId ProjectId, int Quantity);
var line = new OrderLine(ProductId.FromGuid(new Guid("0f8fad5b-d9cb-469f-a165-70867728950e")), ProjectId.FromInt32(42), Quantity: 3);

var yaml = Meziantou.Framework.Yaml.YamlSerializer.Serialize(line);
Assert.Equal("""
    ProductId: 0f8fad5b-d9cb-469f-a165-70867728950e
    ProjectId: 42
    Quantity: 3

    """, yaml);

var deserialized = Meziantou.Framework.Yaml.YamlSerializer.Deserialize<OrderLine>(yaml);
Assert.Equal(line, deserialized);

The converters are public, so you can use them where the attributes are not read, such as JsonSerializerOptions.Converters for a source-generated JsonSerializerContext. To choose another accessibility, declare the converter in the ID (for instance internal sealed partial class ProjectIdJsonConverter;): the generator keeps your modifiers.

Parsing and formatting are culture-invariant: the IFormatProvider arguments of the interface members are ignored and CultureInfo.InvariantCulture is always used. IUtf8SpanParsable, IFormattable, ISpanFormattable and IUtf8SpanFormattable are implemented explicitly, so the type doesn't expose overloads with an IFormatProvider parameter.

IUtf8SpanParsable decodes the UTF-8 text and uses TryParse(ReadOnlySpan) (or TryParse(string)), so both representations accept the same values.

IFormattable, ISpanFormattable and IUtf8SpanFormattable use the following rules:

  • Without a format, the result is the same as ToString(). So, $"{id}" and id.ToString() return the same value.
  • With a format, the format is applied to Value using the invariant culture. For instance, $"{id:N}" returns the Guid without the hyphens. The format is ignored when the underlying type isn't formattable (string, bool, ObjectId).
var id = ProjectId.FromInt32(42);
Assert.Equal("ProjectId { Value = 42 }", $"{id}");
Assert.Equal("00042", $"{id:D5}");

If the Meziantou.Framework.StronglyTypedId.Interfaces NuGet package is present, the generator will implements IStronglyTypedId and IStronglyTypedId.

Supported types

  • System.Boolean
  • System.Byte
  • System.DateTime
  • System.DateTimeOffset
  • System.Decimal
  • System.Double
  • System.Guid
  • System.Half
  • System.Int16
  • System.Int32
  • System.Int64
  • System.Int128
  • System.Numerics.BigInteger
  • System.SByte
  • System.Single
  • System.String
  • System.Uint16
  • System.Uint32
  • System.Uint64
  • System.Uint128
  • MongoDB.Bson.ObjectId

Configuration

You can configure the code generation using the [StronglyTypedIdAttribute] attribute:

[StronglyTypedId(idType: typeof(long),
                 generateSystemTextJsonConverter: true,
                 generateNewtonsoftJsonConverter: true,
                 generateSystemComponentModelTypeConverter: true,
                 generateMongoDBBsonSerialization: true,
                 addCodeGeneratedAttribute: true,
                 GenerateYamlConverter = true,
                 GenerateTomlConverter = true
                 )]
public partial struct ShipmentId { }

When the underlying type is System.Guid, you can choose how the generated New() method creates the value. The default is Version4 (Guid.NewGuid()). Version7 (Guid.CreateVersion7()) requires .NET 9 or later, otherwise the MFSTID0002 diagnostic is reported. None doesn't generate the New() method. The option only applies to System.Guid; using it with another underlying type reports the MFSTID0003 diagnostic:

[StronglyTypedId<Guid>(GuidGenerationStrategy = GuidGenerationStrategy.Version7)]
public partial struct InvoiceId { }

The generated New() method creates a version 7 Guid:

var id = InvoiceId.New(); // Uses Guid.CreateVersion7()
Assert.Equal(7, id.Value.Version);
[StronglyTypedId<Guid>(GuidGenerationStrategy = GuidGenerationStrategy.None)]
public partial struct ExternalId { } // No New() method is generated

You can configure the default value of the options for all the types of an assembly using the [assembly: StronglyTypedIdDefaults] attribute. Options set on [StronglyTypedId] take precedence over the assembly-level defaults:

[assembly: StronglyTypedIdDefaults(GuidGenerationStrategy = GuidGenerationStrategy.Version7,
                                   GenerateNewtonsoftJsonConverter = false,
                                   GenerateMongoDBBsonSerialization = false,
                                   GenerateSystemComponentModelTypeConverter = false,
                                   GenerateSystemTextJsonConverter = true,
                                   AddCodeGeneratedAttribute = true,
                                   StringComparison = StringComparison.Ordinal,
                                   GenerateToStringAsRecord = true)]

namespace Meziantou.Framework.StronglyTypedId.AssemblyDefaults.Samples;

[StronglyTypedId<Guid>]
public partial struct ProjectId { } // New() uses Guid.CreateVersion7()

[StronglyTypedId<Guid>(GuidGenerationStrategy = GuidGenerationStrategy.Version4)]
public partial struct CustomerId { } // New() uses Guid.NewGuid()

You can generate IComparable, IComparable and comparison operators by adding one interface:

[StronglyTypedId<int>]
public partial struct Priority : IComparable { }

The generator adds IComparable, CompareTo and the <, <=, >, >= operators:

var low = Priority.FromInt32(1);
var high = Priority.FromInt32(2);

// IComparable<Priority> and the comparison operators are generated
Assert.True(low < high);
Assert.True(high >= low);
Assert.Equal(-1, low.CompareTo(high));

Additional resources

Analyzer rules

Id Category Description Severity Enabled
MFSTID0001 StronglyTypedId Not supported type Error ✔️
MFSTID0002 StronglyTypedId Guid generation strategy is not supported by the target framework Error ✔️
MFSTID0003 StronglyTypedId Guid generation strategy is only applicable to Guid Warning ✔️
MFSTID0004 StronglyTypedId Generic types are not supported Error ✔️

Downloads by Version

Similar & Alternative Packages

Hand-picked matching NuGet libraries based on tags & ecosystem

Depended On By

Find packages that declare this package as a dependency. NuGet does not provide a reverse-dependency endpoint, so candidates are checked on demand.

Adoption Assessment

A verified publisher signal is available. Assess fit from the package's supported frameworks, license and dependency graph rather than popularity alone.

Compatibility metadata lists 3 target frameworks; confirm the exact target used by your application.

Related Guides & Workflows

Learn how to evaluate, integrate, or audit this package in your .NET project.