Underlying types

edit

An ID wraps one value of a supported type. Any other type makes the analyzer report MFSTID0001, and no code is generated.

Supported types

Underlying typeFactory methodJSON value (System.Text.Json)
boolFromBooleantrue or false
byteFromBytenumber
sbyteFromSBytenumber
shortFromInt16number
ushortFromUInt16number
intFromInt32number
uintFromUInt32number
longFromInt64number
ulongFromUInt64number
Int128FromInt128number, with all its digits
UInt128FromUInt128number, with all its digits
System.Numerics.BigIntegerFromBigIntegernumber, with all its digits
HalfFromHalfnumber
floatFromSinglenumber
doubleFromDoublenumber
decimalFromDecimalnumber
GuidFromGuidstring
stringFromStringstring
DateTimeFromDateTimestring (ISO 8601)
DateTimeOffsetFromDateTimeOffsetstring (ISO 8601)
MongoDB.Bson.ObjectIdFromObjectIdstring

MongoDB.Bson.ObjectId needs a reference to the MongoDB.Bson package. Int128, UInt128 and Half need a target framework that has them.

Pick a type

  • int or long for the keys of a database table that generates them.
  • Guid for IDs created by the application: the generated New() method creates one. See Create Guid values.
  • string for codes and external references (SKUs, country codes, user names from an identity provider). Choose how they are compared with the StringComparison option.

How values are formatted and parsed

ValueAsString, ToString() and the converters that write strings format the value with the invariant culture:

  • Numbers use the invariant culture, without a format: 42, 1.5.
  • Guid uses its default format: 0f8fad5b-d9cb-469f-a165-70867728950e.
  • bool is True or False.
  • DateTime uses the round-trip format ("o"). DateTimeOffset is converted to UTC first, so the offset is not in ValueAsString.

Parse and TryParse read the same representations with the invariant culture:

  • Numbers accept any number style (NumberStyles.Any): signs, thousands separators, decimal points, exponents and surrounding white space.
  • DateTime and DateTimeOffset are adjusted to UTC (DateTimeStyles.AdjustToUniversal).
  • bool and Guid use bool.TryParse and Guid.TryParse.
  • A string ID accepts any string, but not null.

ObjectId IDs have no Parse(ReadOnlySpan<char>) overload and do not implement ISpanParsable<T>, because ObjectId has no such method.