UnitsNet Documentation

repository·master·Indexed 25 days ago

https://github.com/angularsen/unitsnet

A comprehensive .NET library for handling unit conversions and quantity measurements. It provides strongly-typed units (e.g., Length, Mass, Speed), operator overloads for mathematical operations, and support for parsing, formatting, and converting quantities across various physical dimensions. The library includes support for culture-aware localization, dynamic runtime parsing via Quantity and QuantityInfo, and extensibility for custom units.

Tokens
13.2K
Snippets
23
Records
70
Agent score
84%

What's inside UnitsNet

  1. Overview of Units.NET

    master

    Units.NET is a library for handling unit conversions and quantities in .NET. It provides strongly-typed quantities, operator overloads for arithmetic, and support for various unit systems. Key features include:

    • Static Typing: Strongly-typed quantities for different dimensions (e.g., Length, Mass, Pressure).
    • Operator Overloads: Perform arithmetic directly on quantity objects.
    • Culture and Localization: Support for culture-aware formatting and unit names.
    • Dynamic Parsing: Ability to parse quantity strings and convert them to specific units.
    • Extensibility: Support for custom units and runtime custom quantities.
  2. Understand the Quantity and Unit Definition Schema

    master

    Units.NET uses JSON files located in Common/UnitDefinitions to define quantities and their units. Each file describes a single quantity, its associated units, conversion logic, abbreviations, and code-generation behavior.

    Important Constraints:

    • Filenames must follow the pattern <Name>.json (e.g., Length.json).
    • Names must use PascalCase and be valid C# identifiers, as they are used for generated type and member names.
    • The JSON deserializer is permissive; however, you should treat properties marked as required in the schema as mandatory to ensure successful code generation.
  3. Implement UnitToStringConverter for WPF MVVM

    master

    When building WPF applications using the MVVM pattern with UnitsNet, you can use a UnitToStringConverter to handle unit logic in the UI layer. This converter provides the following automated behaviors:

    • Automatic Unit Assignment: If a user enters a numeric value, the unit is automatically assigned based on the current default.
    • Automatic Conversion: If a user enters a unit different from the current default, the value is automatically converted to the target unit.
    • Validation: If a user enters a unit that is incompatible with the current parameter or result, a validation error is triggered.
  4. Define Linear, Affine, and Logarithmic quantities

    master

    When defining quantities in the schema, you can specify different mathematical models:

    Linear Quantities

    This is the default model (e.g., Length, Mass). A quantity is linear if both AffineOffsetType and Logarithmic are omitted. Arithmetic operates directly on converted values.

    Affine Quantities

    Used for scales where differences require a separate quantity type (e.g., Temperature). Set AffineOffsetType to the difference quantity type.

    Logarithmic Quantities

    Used for logarithmic scales (e.g., Decibels). Set Logarithmic to "True" and provide a LogarithmicScalingFactor (as a string). The factor n determines the effective scaling factor S = 10 × n used for arithmetic operations like addition and subtraction.

    Quantity modelJSON valueEffective factorTypical relationship
    Power or generic level11010 × log10(P/P₀)
    Field amplitude (e.g. voltage)22020 × log10(V/V₀)
  5. Update custom quantity implementations for As() and ToUnit() (v6)

    master

    If you have custom quantities that explicitly implement IQuantity.As(), IQuantity.ToUnit(), IQuantity<TUnitType>.As(), or IQuantity<TUnitType>.ToUnit(), you must remove these explicit interface implementations.

    These methods are now handled via QuantityExtensions. If your custom quantity needs to support these conversions, you must register your conversion functions with UnitConverter.Default.

  6. Quick summary of steps to add a new Quantity or Unit

    master

    Units.NET uses a custom CodeGen tool that reads JSON definitions to generate C# code. To add a new quantity or unit, follow these high-level steps:

    1. Modify JSON: Add or change a quantity JSON file in the unit definitions directory.
    2. Generate Code: Run the generate-code.bat script.
    3. Define Tests: Specify test values for the new units in the newly generated test code.
  7. Release new NuGet packages via AppVeyor

    master

    Collaborators can release new NuGet packages by pushing version updates directly to the master branch. The AppVeyor build server automatically builds and attempts to push packages for every push to master. Note that the push will only succeed if the version number has been incremented, as NuGet.org does not allow re-publishing the same version.

    To release:

    1. Bump the version using the provided batch scripts.
    2. Push the commits and annotated git tags to the master branch.
    3. Create a GitHub release by editing the new tag, using a title like UnitsNet/X.Y.Z and including notable commit messages.
    git checkout master
    git pull --fast-forward
    ./Build/bump-version-UnitsNet-minor.bat
    git log
    git push --follow-tags
    git log --oneline --first-parent
  8. Format and Serialize Quantities

    master

    Units.NET supports several ways to handle data output:

    • String Formatting: Use format specifiers and culture-aware settings for outputting quantities.
    • Serialization: Support for JSON, XML, and custom DTO (Data Transfer Object) serialization.
    • Database Persistence: Strategies for saving quantities to a database.
  9. Construct, convert, and use quantities with Static Typing

    master

    UnitsNet provides strongly typed quantity classes (e.g., Length, Mass, Speed) to prevent unit conversion errors and communicate intent.

    Construction

    Length meter = Length.FromMeters(1);
    Length twoMeters = new Length(2, LengthUnit.Meter);

    Conversion

    Access different units via properties on the quantity instance:

    Length meter = Length.FromMeters(1);
    double cm = meter.Centimeters;         // 100
    double yards = meter.Yards;            // 1.09361

    Arithmetic and Operator Overloads

    You can perform arithmetic operations directly on quantities and construct new quantities from the results of operations between different types:

    Length l1 = 2 * Length.FromMeters(1);
    Length l2 = Length.FromMeters(1) / 2;
    Length l3 = l1 + l2;
    
    // Construct between units
    Length distance = Speed.FromKilometersPerHour(80) * TimeSpan.FromMinutes(30);
    Acceleration a1 = Speed.FromKilometersPerHour(80) / TimeSpan.FromSeconds(2);
    // Construct
    Length meter = Length.FromMeters(1);
    Length twoMeters = new Length(2, LengthUnit.Meter);
    
    // Convert
    double cm = meter.Centimeters;         // 100
    double yards = meter.Yards;            // 1.09361
    
    // Arithmetic
    Length l1 = 2 * Length.FromMeters(1);
    Length l2 = Length.FromMeters(1) / 2;
    Length l3 = l1 + l2;
    
    // Construct between units
    Length distance = Speed.FromKilometersPerHour(80) * TimeSpan.FromMinutes(30);