Moonad.Units 0.1.0

dotnet add package Moonad.Units --version 0.1.0
                    
NuGet\Install-Package Moonad.Units -Version 0.1.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Moonad.Units" Version="0.1.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Moonad.Units" Version="0.1.0" />
                    
Directory.Packages.props
<PackageReference Include="Moonad.Units" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Moonad.Units --version 0.1.0
                    
#r "nuget: Moonad.Units, 0.1.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Moonad.Units@0.1.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Moonad.Units&version=0.1.0
                    
Install as a Cake Addin
#tool nuget:?package=Moonad.Units&version=0.1.0
                    
Install as a Cake Tool

Moonad.Units

Version Tests Nuget Buy me a coffee

A simple F#'s units of measure port for C#.

This library brings F#'s units of measure to C#: quantities carry their unit in the type, so mixing meters with seconds is a compile-time error, and the units disappear at run time. It's part of the Moonad project.

using Moonad.Units.SI;

var speed = 100.0.Meters / 9.58.Seconds;   // Quantity<double, MeterPerSecond>
var oops = 100.0.Meters + 9.58.Seconds;    // error CS0019

What's New in 0.1.0

First release:

  • Quantity<T, TUnit>, a zero-cost number tagged with a unit, for any numeric type.
  • Units declared with [Unit], with the * and / operators between them generated by dimensional analysis.
  • Scaled units and exact conversions, such as 3.0.Feet.ToMeters().
  • Temperatures and other units with an offset, as points: 20.0.DegreesCelsius.ToDegreesFahrenheit().
  • The SI units in Moonad.Units.SI, and degrees Fahrenheit and Rankine in Moonad.Units.Imperial.
  • Units shared across projects and packages.
  • An analyzer that explains unit mistakes in terms of units.

See the CHANGELOG for the full history.

Installing

The project's package can be found on Nuget and installed by your IDE or shell as following:

dotnet add package Moonad.Units

or

PM> Install-Package Moonad.Units

Requirements

Moonad.Units requires .NET 10 and C# 14, which is the default language version for net10.0 projects. The operators between units are generated as C# 14 extension operators, so projects using an older language version get the error MU0000.

SI units

The SI units come ready to use in Moonad.Units.SI:

using Moonad.Units.SI;

var force = 80.0.Kilograms * 9.8.MetersPerSecondSquared;   // 784 N
var power = force * 3.0.Meters / 2.0.Seconds;              // 1176 W
var current = 230.0.Volts / 10.0.Ohms;                     // 23 A
var meters = 1.5.Kilometers.ToMeters();                    // 1500 m
Kind Units
Base Meter, Kilogram, Second, Ampere, Kelvin, Mole, Candela
Derived Hertz, Newton, Pascal, Joule, Watt, Coulomb, Volt, Farad, Ohm, Siemens, Weber, Tesla, Henry, Gray, Katal
Common SquareMeter, CubicMeter, MeterPerSecond, MeterPerSecondSquared, KilogramPerCubicMeter
Scaled Kilometer, Centimeter, Millimeter, Gram, Millisecond, Minute, Hour, Liter
Temperature DegreeCelsius, plus DegreeFahrenheit and DegreeRankine in Moonad.Units.Imperial (see Temperatures)

Units that can't be told apart by dimension are left out, since they would make results ambiguous: radian and steradian (dimensionless), becquerel (same as hertz), sievert (same as gray), lumen and lux (their steradian cancels out). Declare them if you need them.

Declaring units

Units are partial structs marked with [Unit]. A source generator does the rest.

Example 1 - Base units:

using Moonad.Units;

[Unit("m")] public partial struct Meter;
[Unit("s")] public partial struct Second;
[Unit("kg")] public partial struct Kilogram;

Example 2 - Derived units:

Of defines a unit from others, with *, /, ^ and parentheses. Like in F#, the operators between related units are found by dimensional analysis, so they don't need to be declared one by one.

[Unit("m/s", Of = "Meter / Second")] public partial struct MeterPerSecond;
[Unit("m/s²", Of = "Meter / Second ^ 2")] public partial struct MeterPerSecondSquared;
[Unit("N", Of = "Kilogram * Meter / Second ^ 2")] public partial struct Newton;
[Unit("J", Of = "Newton * Meter")] public partial struct Joule;
[Unit("Hz", Of = "1 / Second")] public partial struct Hertz;

Example 3 - Scaled units:

Numbers in Of scale a unit. Scales follow the definitions, so Kilometer / Hour knows it's 5/18 of a meter per second:

[Unit("km", Of = "1000 * Meter")] public partial struct Kilometer;
[Unit("h", Of = "3600 * Second")] public partial struct Hour;
[Unit("km/h", Of = "Kilometer / Hour")] public partial struct KilometerPerHour;
[Unit("ft", Of = "0.3048 * Meter")] public partial struct Foot;
[Unit("in", Of = "Foot / 12")] public partial struct Inch;

Example 4 - Building on other units:

Definitions can use the SI units and the units of referenced projects and packages. The operators and conversions between them and your units are generated in your project:

using Moonad.Units.SI;

[Unit("km/h", Of = "Kilometer / Hour")] public partial struct KilometerPerHour;

var trip = 120.0.Kilometers / 1.5.Hours;      // 80 km/h
var speed = trip.ToMetersPerSecond();         // 22.22 m/s

These operators and conversions live in the namespace of your unit, so it must be imported where they're used.

Names in Of resolve to the closest unit: your project's units first, then the ones of referenced projects and packages, then the SI units. So declaring your own Meter is fine, and "Moonad.Units.SI.Meter" still reaches the SI one. Units with the same name in two referenced projects must be qualified, such as "Astronomy.Parsec".

Using quantities

Example 1 - Creating quantities:

Every unit gets a property on numbers, named after its plural (Plural overrides it):

var distance = 100.0.Meters;     // Quantity<double, Meter>
var time = 9.58.Seconds;         // Quantity<double, Second>
var count = 3.Meters;            // Quantity<int, Meter>, any INumber<T> works

Example 2 - Operations:

var speed = distance / time;                         // Quantity<double, MeterPerSecond>
var back = speed * time;                             // Quantity<double, Meter>
var force = 2.0.Kilograms * 9.8.MetersPerSecondSquared;   // Quantity<double, Newton>
var work = force * 10.0.Meters;                      // Quantity<double, Joule>
double ratio = distance / 50.0.Meters;               // same unit: no unit left
double cycles = 50.0.Hertz * 2.0.Seconds;            // dimensionless

Quantities of the same unit can be added, subtracted, compared and multiplied or divided by numbers.

Example 3 - Mistakes don't compile:

var a = distance + time;                         // error CS0019
Quantity<double, Meter> b = distance / time;     // error CS0029

Next to each compiler error, an analyzer explains it in terms of units:

error CS0019: Operator '+' cannot be applied to operands of type 'Quantity<double, Meter>' and 'Quantity<double, Second>'
error MU0005: Can't add 'Second' (s) to 'Meter' (m): they have different dimensions

error CS0019: Operator '+' cannot be applied to operands of type 'Quantity<double, Meter>' and 'Quantity<double, Foot>'
error MU0005: Can't add 'Foot' (ft) to 'Meter' (m) without converting one of them first, such as with ToMeters()

error CS0019: Operator '/' cannot be applied to operands of type 'Quantity<double, Meter>' and 'Quantity<double, Hour>'
error MU0006: Can't divide 'Meter' (m) by 'Hour' (h): no unit is declared as Meter / Hour; declare one with Of = "Meter / Hour", or convert the operands first so the result is 'MeterPerSecond' (m/s)

Example 4 - Conversions:

Every unit gets a To method for each unit of the same dimension, named after its plural:

var meters = 3.0.Feet.ToMeters();                    // 0.9144 m
var speed = 36.0.KilometersPerHour.ToMetersPerSecond();   // 10 m/s
var trip = 120.0.Kilometers / 1.5.Hours;             // 80 km/h, operators keep the scale
var oops = 1.0.Kilometers + 1.0.Meters;              // error CS0019: convert first

Like in F#, units are never converted implicitly. Units with the same dimension and scale, such as Hertz and Becquerel, are kept apart: they don't convert to each other. Factors are exact fractions, applied as a multiplication followed by a division, so decimal quantities stay exact; for integer quantities the division truncates (2999.Meters.ToKilometers() is 2 km).

Example 5 - Leaving the unit:

double meters = distance.Value;
Console.WriteLine(speed);    // "10.438413361169102 m/s"

Temperatures

Degrees Celsius and Fahrenheit have an offset: 0 °C is 273.15 K, not 0 K. So their values are points on a scale, QuantityPoint<T, TUnit>, and their differences are ordinary quantities, like DateTime and TimeSpan:

using Moonad.Units.SI;          // Kelvin, DegreeCelsius
using Moonad.Units.Imperial;    // DegreeFahrenheit, DegreeRankine

var room = 20.0.DegreesCelsius;
var fever = 102.2.DegreesFahrenheit;

var f = room.ToDegreesFahrenheit();             // 68 °F
var k = room.ToKelvins();                       // 293.15 K, a Quantity: use it in formulas
var c = fever.ToDegreesCelsius();               // 39 °C
Quantity<double, Kelvin> rise = c - room;       // 19 K: point − point is a difference
var warmer = room + 5.0.Kelvins;                // 25 °C: point + difference is a point
var cold = (-40.0).DegreesCelsius;              // parentheses for negative points
var body = 37m.DegreesCelsius.ToDegreesFahrenheit();   // 98.6 °F, exact in decimal

Adding, multiplying, dividing or negating points doesn't compile, since the result would depend on where the zero is (10 °C + 10 °C isn't 20 °C, it's 293.15 °C):

error MU0005: Can't add 'DegreeCelsius' (°C) to 'DegreeCelsius' (°C): values of a unit with an offset are points on a scale and can't be added; subtract them to get a difference in 'Kelvin' (K), or add a difference to one of them
error MU0005: Can't multiply 'DegreeCelsius' (°C) by a number without a unit: values of a unit with an offset can't be multiplied or divided, since the result would depend on where its zero is; convert it first to a unit without one, such as with ToKelvins()
error MU0005: Can't negate 'DegreeCelsius' (°C): values of a unit with an offset have no opposite, since it would depend on where its zero is; for a negative value, write (-40.0).DegreesCelsius

Conversions with an offset use exact integer constants ((x * 5 - 160) / 9 for °F to °C), so use double, decimal, int or long with them, not byte or unsigned types.

Differences of degrees Celsius are in kelvins and differences of degrees Fahrenheit in degrees Rankine, the units with the same size of degree and no offset. Declare other scales with Zero, where the zero of the scale is, and Of, the size of its degree, which must match a unit without an offset:

// Réaumur: water freezes at 0 °Ré and boils at 80 °Ré
[Unit("Ré", Of = "5 / 4 * Kelvin")] public partial struct ReaumurDegree;
[Unit("°Ré", Of = "ReaumurDegree", Zero = "273.15 * Kelvin")] public partial struct DegreeReaumur;

var boiling = 100.0.DegreesCelsius.ToDegreesReaumur();   // 80 °Ré

Zero cost

Quantity<T, TUnit> and QuantityPoint<T, TUnit> are readonly structs holding only the number: Quantity<double, Meter> has the size of a double, and the unit exists only for the compiler.

The benchmarks in bench/ run the same loops over 1024 values with raw doubles and with quantities:

Category double Quantity Ratio Allocated
Distance (Σ speed × time) 371.4 ns 366.7 ns 0.99 -
Force (max of mass × acceleration) 491.4 ns 489.3 ns 1.00 -
Conversion (Σ km to m) 353.3 ns 354.1 ns 1.00 -
Temperature (Σ °F to °C) 731.4 ns 731.2 ns 1.00 -

<sub>BenchmarkDotNet 0.15.8, .NET 10.0.15, Intel Core i9-13900KS, Linux.</sub>

Diagnostics

Id Severity Meaning
MU0000 Error The project doesn't use C# 14
MU0001 Error A unit isn't partial
MU0002 Error An Of or Zero definition is invalid, unknown, ambiguous or circular
MU0003 Warning Two units have the same dimension and scale, so operations resulting in them and conversions between them aren't generated
MU0004 Error A unit is nested or generic
MU0005 Error Explains a compiler error between quantities whose units don't match
MU0006 Error Explains a compiler error on * or / whose result isn't a declared unit
MU0007 Error A Quantity of a unit with an offset, or a QuantityPoint of a unit without one
Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net10.0

    • No dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.1.0 0 11/30/2026