Skip to content

Proposal: units as objects in v6 (UnitOf<TQuantity> instead of unit enums) #1740

Description

@tmilnthorp

Why

Units are enums today, which makes them closed:

#1738 introduced UnitOf<TQuantity>, a unit described by its names and conversions and tied to its quantity. This proposal makes UnitOf<TQuantity> the unit type in v6.

Where it ends up

  • Built-in units are UnitOf objects, LengthUnits.Meter, replacing LengthUnit.Meter.
  • Quantities store their unit as a UnitOf: Length.Unit is a UnitOf<Length>.
  • Custom units are first-class: registered once, then converted, parsed, formatted and stored like built-in units, with real names.
  • UnitKey goes away, because the unit object itself is the identity.
  • Serialization uses unit names, and old numeric values stay readable for one major version.

Why LengthUnits.Meter, not Length.Meter: 80 units in 24 quantities have identical singular and plural names, so a static Frequency.Hertz would collide with the existing value property frequency.Hertz.

Steps

Each is a small PR. Only the last one is breaking.

  1. Generate every unit as a UnitOf (additive), e.g. LengthUnits.Meter, next to the enums. The default unit mappings are built from these, so each unit's data is generated in one place. Draft: Generate units as UnitOf<TQuantity>, such as LengthUnits.Meter #1741.
  2. Unit-agnostic tests (no product change): tests pass units by name instead of enum constants in [InlineData], switch and int casts.
  3. Register custom units with a setup (additive): parsing and formatting by abbreviation.
  4. The switch (breaking): quantities store UnitOf, the enums are marked obsolete, and UnitKey is removed.
    Generated quantities then also implement IQuantityOfType.Create/Info explicitly: in a prototype, class-based units combined with those static default interface implementations made the runtime's type loader need more than 2 MB of stack to load one quantity.

Upgrade path

If this direction is accepted, I'd add a v5 bridge:

  • LengthUnits.Meter and friends shipped next to the enums in a v5 minor;
  • an analyzer whose code fix rewrites LengthUnit.X to LengthUnits.X.

Code migrated on v5 would then compile unchanged on v6. #1739 (UnitOf for v5) is the first piece of that bridge.

Feedback wanted

  • The direction: units as objects, replacing the enums in v6.
  • The name: LengthUnits.Meter.
  • Timing: should step 4 land in v6 (v6 Release #1200), or wait for v7?

Related: #1738, #1737, #1739, #1246, #1562, #1200

No activity

Activity on this issue will appear here.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions