### Install Units.NET via CLI Source: https://github.com/angularsen/unitsnet/blob/master/README.md Use the dotnet CLI to add the UnitsNet package to your project. ```bash dotnet add package UnitsNet ``` -------------------------------- ### Common String Formatting Examples in C# Source: https://github.com/angularsen/unitsnet/blob/master/Docs/string-formatting.md Demonstrates typical, localized, and converted string representations of a Length unit. Assumes US English culture by default. ```csharp var length = Length.FromCentimeters(3.14159265358979); // Typical formats length.ToString(); // 3.14 cm length.ToString("s4"); // 3.1416 cm // Localized length.ToString(new CultureInfo("nb-NO")); // 3,14 cm length.ToString(new CultureInfo("ru-RU")); // 3,14 sm (Cyrillic) // Converted length.As(LengthUnit.Meters).ToString(); // 0.13 m ``` ```csharp // Use .NET's built-in formatting methods Console.WriteLine("Length is {0:v} {0:a}", l); // "Length is 3.14159265358979 ft" string.Format("Length is {0:v} {0:a}", l); // "Length is 3.14159265358979 ft" $"Length is {l:v} {l:a}"; // "Length is 3.14159265358979 ft" ``` -------------------------------- ### Common String Formatting Examples in C# Source: https://github.com/angularsen/unitsnet/wiki/String-Formatting Demonstrates typical string formatting for units, including default, specific precision, localized cultures, unit conversions, and using .NET's built-in formatting methods. ```csharp var length = Length.FromCentimeters(3.14159265358979); // Typical formats length.ToString(); // 3.14 cm length.ToString("s4"); // 3.1416 cm // Localized length.ToString(new CultureInfo("nb-NO")); // 3,14 cm length.ToString(new CultureInfo("ru-RU")); // 3,14 см // Converted length.As(LengthUnit.Meters).ToString(); // 0.13 m // Use .NET's built-in formatting methods Console.WriteLine("Length is {0:v} {0:a}", l); // "Length is 3.14159265358979 ft" string.Format("Length is {0:v} {0:a}", l); // "Length is 3.14159265358979 ft" $"Length is {l:v} {l:a}"; // "Length is 3.14159265358979 ft" ``` -------------------------------- ### Culture and Localization Examples in C# Source: https://github.com/angularsen/unitsnet/blob/master/README.md Demonstrates how to use CultureInfo for formatting unit abbreviations and values, and parsing unit strings. Note that CurrentCulture affects number formatting in ToString() unless a specific culture is provided. ```C# var usEnglish = new CultureInfo("en-US"); var russian = new CultureInfo("ru-RU"); var oneKg = Mass.FromKilograms(1); // ToString() uses CurrentCulture for abbreviation language number formatting. This is consistent with the behavior of the .NET Framework, // where DateTime.ToString() uses CurrentCulture for the whole string, likely because mixing an english date format with a russian month name might be confusing. CultureInfo.CurrentCulture = russian; string kgRu = oneKg.ToString(); // "1 кг" // ToString() with specific culture and custom string format pattern string mgUs = oneKg.ToUnit(MassUnit.Milligram).ToString(usEnglish, "unit: {1}, value: {0:F2}"); // "unit: mg, value: 1.00" string mgRu = oneKg.ToUnit(MassUnit.Milligram).ToString(russian, "unit: {1}, value: {0:F2}"); // "unit: мг, value: 1,00" // Parse measurement from string Mass kg = Mass.Parse("1.0 kg", usEnglish); // Parse unit from string, a unit can have multiple abbreviations RotationalSpeedUnit rpm1 = RotationalSpeed.ParseUnit("rpm"); // RotationalSpeedUnit.RevolutionPerMinute RotationalSpeedUnit rpm2 = RotationalSpeed.ParseUnit("r/min"); // RotationalSpeedUnit.RevolutionPerMinute // Get default abbreviation for a unit, the first if more than one is defined in Length.json for Kilogram unit string kgAbbreviation = Mass.GetAbbreviation(MassUnit.Kilogram); // "kg" ``` -------------------------------- ### Convert Between Custom Units Using UnitConverter Source: https://github.com/angularsen/unitsnet/wiki/Extending-with-Custom-Units Demonstrates converting a quantity from one custom unit to another using the previously defined conversion functions in UnitConverter. This example converts '10 tons' to 'Some' and 'Lots' units. ```csharp var from = new HowMuch(10, HowMuchUnit.Tons); IQuantity Convert(HowMuchUnit toUnit) => unitConverter.GetConversionFunction(from.Unit, toUnit)(from); Console.WriteLine($"Convert 10 tons to:"); Console.WriteLine(Convert(HowMuchUnit.Some)); // 200 sm Console.WriteLine(Convert(HowMuchUnit.Lots)); // 100 lts Console.WriteLine(Convert(HowMuchUnit.Tons)); // 10 tns ``` -------------------------------- ### Standard Numeric Formatting Examples in C# Source: https://github.com/angularsen/unitsnet/wiki/String-Formatting Illustrates the use of standard numeric format specifiers for units, including general ('g'), fixed-point ('f'), scientific ('e'), round-trip ('r'), and custom formats like '#.0' and '00000.0'. ```csharp Length.FromFeet(Math.PI).ToString("g") ``` ```csharp Length.FromFeet(Math.PI).ToString("f") ``` ```csharp Length.FromFeet(Math.PI).ToString("f1") ``` ```csharp Length.FromFeet(Math.PI).ToString("r") ``` ```csharp Length.FromFeet(Math.PI).ToString("e2") ``` ```csharp Length.FromFeet(Math.PI).ToString("#.0") ``` ```csharp Length.FromFeet(Math.PI).ToString("00.0") ``` -------------------------------- ### Constructing Quantities Source: https://context7.com/angularsen/unitsnet/llms.txt Demonstrates how to create instances of physical quantities using constructors or static factory methods. ```APIDOC ## Constructing Quantities Every quantity type provides both a constructor and static factory methods to build instances from a value and a unit. ```csharp using UnitsNet; using UnitsNet.Units; // Constructor: explicit value + unit Length a = new Length(5.0, LengthUnit.Meter); // Static factory method (preferred, more readable) Length b = Length.FromMeters(5.0); Length c = Length.FromCentimeters(500); Length d = Length.FromFeet(16.4042); Mass kg = Mass.FromKilograms(70); Mass g = Mass.FromGrams(70_000); // From a unit enum value + value (dynamic) IQuantity qty = Length.From(5.0, LengthUnit.Meter); // Using UnitSystem (SI, CGS, etc.) Length si = new Length(1.0, UnitSystem.SI); // => 1 m (meter is SI base unit for length) Console.WriteLine(b); // 5 m Console.WriteLine(c); // 500 cm Console.WriteLine(kg); // 70 kg ``` ``` -------------------------------- ### Configure UnitsNet Globally Source: https://context7.com/angularsen/unitsnet/llms.txt Modify UnitsNetSetup.Default to add custom units or abbreviations globally. This setup affects all subsystems like UnitConverter, UnitAbbreviationsCache, and parsers. ```csharp using UnitsNet; using UnitsNet.Units; // Access the global default setup UnitsNetSetup setup = UnitsNetSetup.Default; // All subsystems accessible from the setup UnitConverter converter = setup.UnitConverter; UnitAbbreviationsCache abbrevs = setup.UnitAbbreviations; UnitParser unitParser = setup.UnitParser; QuantityParser qtyParser = setup.QuantityParser; QuantityInfoLookup quantities = setup.Quantities; // Add a custom abbreviation globally abbrevs.MapUnitToDefaultAbbreviation(LengthUnit.Meter, "metres"); Console.WriteLine(Length.FromMeters(1).ToString()); // "1 metres" (uses the new default) // Register a custom conversion converter.SetConversionFunction( LengthUnit.Hand, LengthUnit.Inch, q => new Length(q.Value * 4, LengthUnit.Inch) // 1 hand = 4 inches ); // Create an isolated setup (does not affect the global default) var customConverter = UnitConverter.CreateDefault(); var isolated = new UnitsNetSetup(Quantity.DefaultProvider.Quantities, customConverter); IQuantity parsed = isolated.QuantityParser.Parse( "10 km", formatProvider: null, fromDelegate: Length.From ); Console.WriteLine(parsed); // 10 km ``` -------------------------------- ### DataContractJsonSerializer Schema for JSON Source: https://github.com/angularsen/unitsnet/blob/master/Docs/serialization.md Example schema for JSON serialization using `DataContractJsonSerializer`. Note that enum values are serialized as integers, which is not recommended due to potential instability. ```json { "__type": "Information:#UnitsNet", "Value": 1.20, "Unit": 4 } ``` -------------------------------- ### Constructing Quantities in Units.NET Source: https://context7.com/angularsen/unitsnet/llms.txt Demonstrates how to create quantity instances using constructors or static factory methods. Static factory methods are generally preferred for readability. Supports explicit value and unit, or dynamic creation with UnitSystem. ```csharp using UnitsNet; using UnitsNet.Units; // Constructor: explicit value + unit Length a = new Length(5.0, LengthUnit.Meter); // Static factory method (preferred, more readable) Length b = Length.FromMeters(5.0); Length c = Length.FromCentimeters(500); Length d = Length.FromFeet(16.4042); Mass kg = Mass.FromKilograms(70); Mass g = Mass.FromGrams(70_000); // From a unit enum value + value (dynamic) IQuantity qty = Length.From(5.0, LengthUnit.Meter); // Using UnitSystem (SI, CGS, etc.) Length si = new Length(1.0, UnitSystem.SI); // => 1 m (meter is SI base unit for length) Console.WriteLine(b); // 5 m Console.WriteLine(c); // 500 cm Console.WriteLine(kg); // 70 kg ``` -------------------------------- ### Get All Quantity Names Source: https://github.com/angularsen/unitsnet/blob/master/README.md Retrieve all available quantity names for use in UI elements like dropdowns. This can be done by accessing the `Quantity.Names` property or by selecting names from `Quantity.Infos`. ```csharp this.Quantities = Quantity.Names; // string[] ``` ```csharp // or this.Quantities = Quantity.Infos.Select(i => i.Name).ToList(); ``` -------------------------------- ### Constructing and Converting Length Quantities Source: https://github.com/angularsen/unitsnet/blob/master/README.md Demonstrates how to construct Length quantities using static methods or constructors and how to convert them to different units. It also shows how passing quantity types instead of raw values can prevent errors. ```csharp // 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 double feet = meter.Feet; // 3.28084 double inches = meter.Inches; // 39.3701 // Pass quantity types instead of values to avoid conversion mistakes and communicate intent string PrintPersonWeight(Mass weight) { // Compile error! Newtons belong to Force, not Mass. A common source of confusion. double weightNewtons = weight.Newtons; // Convert to the unit of choice - when you need it return $"You weigh {weight.Kilograms:F1} kg."; } ``` -------------------------------- ### Convert Between Units Source: https://github.com/angularsen/unitsnet/blob/master/README.md Perform unit conversions using the `UnitConverter` class. Provide the numeric value, the source unit enum, and the target unit enum to get the converted value. ```csharp double convertedValue = UnitConverter.Convert( FromValue, // numeric value SelectedFromUnit.UnitEnumValue, // Enum, such as LengthUnit.Meter SelectedToUnit.UnitEnumValue)); // Enum, such as LengthUnit.Centimeter ``` -------------------------------- ### Construct Quantities with Number Extension Methods Source: https://context7.com/angularsen/unitsnet/llms.txt Use extension methods on numeric types to fluently construct UnitsNet quantities. Works with any numeric type implementing INumber or IConvertible. Requires installing the UnitsNet.NumberExtensions package. ```csharp // Install: dotnet add package UnitsNet.NumberExtensions using UnitsNet.NumberExtensions.NumberToLength; using UnitsNet.NumberExtensions.NumberToMass; using UnitsNet.NumberExtensions.NumberToPressure; // Classic extension-method syntax (C# 13 and below) Length distance = 5.0.Meters(); // Length: 5 m Length height = 180.Centimeters(); // Length: 180 cm Mass weight = 70.Kilograms(); // Mass: 70 kg Pressure pressure = 101325.Pascals(); // Pressure: 101325 Pa // Works with any numeric type implementing INumber (.NET 7+) or IConvertible int intVal = 42; Length fromInt = intVal.Meters(); // Length: 42 m float floatVal = 9.81f; Acceleration g = floatVal.MetersPerSecondSquared(); // Acceleration: 9.81 m/s² // C# 14 extension-member syntax (UnitsNet.NumberExtensions.CS14, requires LangVersion preview) // using UnitsNet.NumberExtensions.NumberToLength; // Length noParens = 5.0.Meters; ← no parentheses in C# 14 // Chaining / calculation Speed velocity = 100.0.Kilometers() / Duration.FromHours(1); // 100 km/h → Speed Console.WriteLine(velocity.MetersPerSecond); // 27.7778 ``` -------------------------------- ### Constructing Quantities with UnitSystem Source: https://github.com/angularsen/unitsnet/blob/master/Docs/adding-a-new-unit.md Demonstrates how to construct quantities using a specified UnitSystem, such as SI or a custom British Engineering unit system. This requires the unit to have a BaseUnits definition. ```csharp new Length(1, UnitSystem.SI).ToString() // "1 m" new Length(1, myBritishEngineeringUnitSystem).ToString() // "1 ft" ``` -------------------------------- ### Compare Quantities with Tolerance Source: https://context7.com/angularsen/unitsnet/llms.txt Demonstrates exact and tolerance-based equality checks for quantities, as well as comparison operators. Use `Equals` for physical equality and `==` for structural equality. ```csharp using UnitsNet; Length a = Length.FromMeters(1.0); Length b = Length.FromCentimeters(100); // also 1 m Length c = Length.FromMeters(1.5); // Exact equality (value + unit; a and b are structurally different but represent the same physical length) bool structuralEq = a == b; // false (different units stored) bool physicalEq = a.Equals(b); // true (compares via base unit) // Relative tolerance (within 1%) bool withinRelTol = a.Equals(b, 0.01, ComparisonType.Relative); // true // Absolute tolerance (within 0.001 m) bool withinAbsTol = a.Equals(b, 0.001, ComparisonType.Absolute); // true // Comparison operators bool greater = c > a; // true bool less = a < c; // true int cmp = a.CompareTo(c); // -1 // Comparison helper (raw doubles) bool equalDoubles = Comparison.Equals(1.0, 1.009, 0.01, ComparisonType.Relative); // true Console.WriteLine($"a.Equals(b) = {a.Equals(b)}"); // true Console.WriteLine($"c > a = {c > a}"); // true ``` -------------------------------- ### Dynamic Quantity Construction with Quantity.From Source: https://context7.com/angularsen/unitsnet/llms.txt Construct quantities at runtime using enum values, unit names, or abbreviations. Use TryFrom variants for safe construction. ```csharp using UnitsNet; using UnitsNet.Units; // Construct from enum value IQuantity q1 = Quantity.From(3.0, LengthUnit.Centimeter); // Length: 3 cm // Construct from quantity name + unit name strings IQuantity q2 = Quantity.From(3.0, "Length", "Centimeter"); // Length: 3 cm // Construct from unit abbreviation string IQuantity q3 = Quantity.FromUnitAbbreviation(90.0, "kg"); // Mass: 90 kg // TryFrom variants (safe) if (Quantity.TryFrom(5.0, "Mass", "Gram", out IQuantity? qty)) Console.WriteLine(qty); // 5 g // Parse from string to typed quantity IQuantity parsed = Quantity.Parse(typeof(Length), "1.5 km"); // Length: 1.5 km // Enumerate all registered quantities and their units foreach (QuantityInfo info in Quantity.Infos) { Console.WriteLine($"{info.Name}: base unit = {info.BaseUnitInfo.Name}, unit count = {info.UnitInfos.Length}"); } // Output (excerpt): // Length: base unit = Meter, unit count = 41 // Mass: base unit = Kilogram, unit count = 35 // Look up by name QuantityInfo lengthInfo = Quantity.ByName["Length"]; UnitInfo cmInfo = Quantity.GetUnitInfo(LengthUnit.Centimeter); Console.WriteLine(cmInfo.Name); // "Centimeter" Console.WriteLine(cmInfo.PluralName); // "Centimeters" ``` -------------------------------- ### Build Project with .NET CLI Source: https://github.com/angularsen/unitsnet/blob/master/CLAUDE.md Builds the entire UnitsNet solution using the .NET CLI. This command compiles all projects within the solution. ```bash dotnet build UnitsNet.slnx ``` -------------------------------- ### Typical Git Commands for Releasing Nugets Source: https://github.com/angularsen/unitsnet/blob/master/Docs/collaborators/releasing-nugets.md Use these commands to checkout the master branch, pull the latest changes, bump the version, and push the new version with tags to the repository. ```bash git checkout master # Checkout master git pull --fast-forward # Pull latest origin/master, fail if there are local commits ./Build/bump-version-UnitsNet-minor.bat # Increase the version and create an annotated git tag git log # Verify that it is only the version commit about to be pushed git push --follow-tags # Push commits and tags git log --oneline --first-parent # Compact log for copy & paste of commits into release page, see below ``` -------------------------------- ### Construct Quantity from Value and Unit Enum Source: https://github.com/angularsen/unitsnet/blob/master/README.md Create a quantity instance by providing a numeric value and a unit enumeration. Use `TryFrom` for fallible construction. ```csharp IQuantity quantity = Quantity.From(3, LengthUnit.Centimeter); // Length if (Quantity.TryFrom(3, LengthUnit.Centimeter, out IQuantity quantity2)) { } ``` -------------------------------- ### Push NuGet Packages using Batch Script Source: https://github.com/angularsen/unitsnet/wiki/Collaborators:-Release-New-Nuget Execute the provided batch script to push all generated NuGet packages. This script is located in the /Build directory. ```bash /Build/push-nugets.bat ``` -------------------------------- ### Run Performance Benchmarks Source: https://github.com/angularsen/unitsnet/blob/master/CLAUDE.md Executes performance benchmarks for the UnitsNet library. Results are saved in the Artifacts folder. ```bash dotnet run -c Release --project UnitsNet.Benchmark ``` -------------------------------- ### Build Project with Batch Script Source: https://github.com/angularsen/unitsnet/blob/master/CLAUDE.md Builds the UnitsNet project using a convenience batch script. This is an alternative to using the .NET CLI directly for building. ```batch build.bat ``` -------------------------------- ### Quantity and Unit Name Formatting in C# Source: https://github.com/angularsen/unitsnet/blob/master/Docs/string-formatting.md Demonstrates formatting the quantity type name using 'q' and the unit name using 'u'. ```csharp Length.FromFeet(Math.PI).ToString("q") // Quantity name: Length Mass.FromTonnes(Math.PI).ToString("u") // Unit name: Tonne ``` -------------------------------- ### Set NuGet API Key Source: https://github.com/angularsen/unitsnet/blob/master/Docs/collaborators/releasing-nugets.md Sets your NuGet API key on your local machine. This is required before pushing packages. ```bash nuget setApiKey Your-API-Key ``` -------------------------------- ### Compile and Run Code Generator Source: https://github.com/angularsen/unitsnet/blob/master/CodeGen/README.md Compile and run the code generator directly from the source directory. ```cmd cd /dev/UnitsNet/CodeGen dotnet run ``` -------------------------------- ### Construct Quantity from Value, Quantity Name, and Unit Name Source: https://github.com/angularsen/unitsnet/blob/master/README.md Construct a quantity using string representations for quantity and unit names. `TryFrom` is available for safe parsing. ```csharp IQuantity quantity = Quantity.From(value: 3, quantityName: "Length", unitName: "Centimeter"); if (Quantity.TryFrom(value: 3, quantityName: "Length", unitName: "Centimeter", out IQuantity? quantity2)) { } ``` -------------------------------- ### Build All Targets including nanoFramework Source: https://github.com/angularsen/unitsnet/blob/master/CLAUDE.md Builds the project for all targets, including the .NET nanoFramework. Use this when targeting embedded systems. ```batch build-all-targets.bat ``` -------------------------------- ### Quantity and Unit Name Formatting in C# Source: https://github.com/angularsen/unitsnet/wiki/String-Formatting Demonstrates formatting units to output the quantity name ('q') or the unit name ('u'). This is useful for displaying the type of measurement or the specific unit used. ```csharp Length.FromFeet(Math.PI).ToString("q") ``` ```csharp Mass.FromTonnes(Math.PI).ToString("u") ``` ```csharp Length.FromFeet(Math.PI).ToString("u") ``` ```csharp Mass.FromTonnes(Math.PI).ToString("u") ``` -------------------------------- ### Format Quantities to Strings Source: https://context7.com/angularsen/unitsnet/llms.txt Shows how to format quantity values and units using standard and custom specifiers, including culture-sensitive formatting and interpolation. Use `ToString` with format specifiers for custom output. ```csharp using System.Globalization; using UnitsNet; using UnitsNet.Units; Length l = Length.FromCentimeters(3.14159265358979); // Default: 2 significant digits after radix Console.WriteLine(l.ToString()); // "3.14 cm" Console.WriteLine(l.ToString("s4")); // "3.1416 cm" // Standard numeric specifiers (value + unit) Console.WriteLine(l.ToString("f1")); // "3.1 cm" Console.WriteLine(l.ToString("e2")); // "3.14e+000 cm" Console.WriteLine(l.ToString("r")); // "3.14159265358979 cm" // Unit abbreviation only Console.WriteLine(l.ToString("a")); // "cm" Console.WriteLine(l.ToString("a1")); // "'" (alternate abbreviation for feet) // Quantity name / unit name Console.WriteLine(l.ToString("q")); // "Length" Console.WriteLine(l.ToString("u")); // "Centimeter" // Culture-sensitive var russian = new CultureInfo("ru-RU"); Console.WriteLine(l.ToString(russian)); // "3,14 sm" (Cyrillic) // Interpolation and string.Format Console.WriteLine($"{l:f2}"); // "3.14 cm" Console.WriteLine(string.Format("{0:v} {0:a}", l)); // "3.14159265358979 cm" // Get abbreviation programmatically string abbrev = Length.GetAbbreviation(LengthUnit.Kilometer); // "km" ``` -------------------------------- ### Runtime Quantity and Unit Lookup in C# Source: https://github.com/angularsen/unitsnet/blob/master/README.md Shows how to use the Quantity class to dynamically look up information about quantities, units, and their properties at runtime. This is useful for scenarios like parsing user input or populating UI elements. ```C# string[] names = Quantity.Names; // ["Length", "Mass", ...] QuantityInfo[] qis = Quantity.Infos; // All quantities and their units, types, values. // Look up quantity by name. QuantityInfo lengthInfo = Quantity.ByName["Length"]; UnitInfo[] lengthUnits = lengthInfo.UnitInfos; // Look up unit by enum value (note: for extensibility, will instead look up by name in the future) UnitInfo cmInfo = Quantity.GetUnitInfo(LengthUnit.Centimeter); ``` -------------------------------- ### Publish and Run Code Generator Executable Source: https://github.com/angularsen/unitsnet/blob/master/CodeGen/README.md Publish the code generator as a self-contained executable and then run it. ```cmd cd /dev/UnitsNet/CodeGen dotnet publish -c Release -r win10-x64 cd ../Artifacts/CodeGen/netcoreapp2.1/win10-x64/ CodeGen.exe ``` -------------------------------- ### Add Remote and Fetch Source: https://github.com/angularsen/unitsnet/wiki/Adding-a-New-Unit Commands to add the main repository as a remote named 'angularsen' and fetch its branches and tags. This is useful for keeping your fork up-to-date. ```sh # Add main repo as a remote named 'angularsen' git add remote angularsen https://github.com/angularsen/UnitsNet # Fetch branches/tags from all your remotes git fetch ``` -------------------------------- ### Map Unit Abbreviations and Parse Custom Units Source: https://github.com/angularsen/unitsnet/blob/master/README.md Customize unit abbreviations and parse them using `UnitsNetSetup`. This allows for runtime definition of unit mappings. ```csharp // Map unit enum values to unit abbreviations var unitAbbreviations = UnitsNetSetup.Default.UnitAbbreviations; unitAbbreviations.MapUnitToDefaultAbbreviation(HowMuchUnit.Some, "sm"); unitAbbreviations.GetDefaultAbbreviation(HowMuchUnit.Some); // "sm" UnitsNetSetup.Default.UnitParser.Parse("sm"); // HowMuchUnit.Some ``` -------------------------------- ### PowerShell for .NET CLI Parameter Suggestions Source: https://github.com/angularsen/unitsnet/blob/master/CodeGen/README.md Use PowerShell to publish the code generator and test .NET CLI parameter suggestions, such as --version and --verbose. ```powershell cd /dev/UnitsNet/CodeGen dotnet publish -c Release -r win10-x64 CodeGen cd ../Artifacts/CodeGen/netcoreapp2.1/win10-x64/ CodeGen.exe --ver ``` -------------------------------- ### Run Tests with Batch Script Source: https://github.com/angularsen/unitsnet/blob/master/CLAUDE.md Runs all unit tests using a convenience batch script. This is an alternative to using the .NET CLI directly for testing. ```batch test.bat ``` -------------------------------- ### Creating and Pushing a New Branch to Your Fork Source: https://github.com/angularsen/unitsnet/blob/master/Docs/collaborators/releasing-nugets.md Create a new branch based on the remote master, make commits, and push it to your fork ('my') to prepare for a pull request. ```bash git checkout -b new-branch origin/master # new branch, based on remote master # Add some commits... git push my new-branch # push branch to your fork # Create PR from your fork's github web page ``` -------------------------------- ### Parse Quantities and Units from Strings Source: https://context7.com/angularsen/unitsnet/llms.txt Explains how to parse quantity values and unit abbreviations from strings using static `Parse`/`TryParse` methods and `UnitParser`. Handles potential `AmbiguousUnitParseException` for ambiguous abbreviations. ```csharp using System.Globalization; using UnitsNet; using UnitsNet.Units; // Parse a quantity from string Length parsed = Length.Parse("5.5 m"); Length parsedC = Length.Parse("200 cm", CultureInfo.GetCultureInfo("en-US")); // TryParse (safe) if (Length.TryParse("1ft 2in", out Length imperial)) { Console.WriteLine(imperial.Feet); // 1.1667 (combined feet+inches) } // Parse just the unit abbreviation LengthUnit unit1 = Length.ParseUnit("m"); // LengthUnit.Meter LengthUnit unit2 = Length.ParseUnit("km"); // LengthUnit.Kilometer bool ok = Length.TryParseUnit("cm", out LengthUnit unit3); // true, Centimeter // Using UnitParser directly (works for any unit enum type) LengthUnit km = UnitsNetSetup.Default.UnitParser.Parse("km"); // Ambiguous abbreviation throws AmbiguousUnitParseException try { Length.Parse("1 pt"); // "pt" could be DtpPoint or PrinterPoint } catch (AmbiguousUnitParseException ex) { Console.WriteLine(ex.Message); // "Cannot parse 'pt' since it could be either of these: DtpPoint, PrinterPoint" } Console.WriteLine(parsed); // 5.5 m Console.WriteLine(parsedC); // 200 cm ``` -------------------------------- ### Push NuGet Packages using dotnet CLI Source: https://github.com/angularsen/unitsnet/blob/master/Docs/collaborators/releasing-nugets.md Pushes NuGet packages located in the /Artifacts/NuGet folder using the dotnet CLI. Ensure you have set your API key first. ```bash dotnet nuget push ``` -------------------------------- ### Run All Tests with .NET CLI Source: https://github.com/angularsen/unitsnet/blob/master/CLAUDE.md Executes all unit tests in the UnitsNet solution using the .NET CLI. This command is essential for verifying code changes. ```bash dotnet test UnitsNet.slnx ``` -------------------------------- ### UnitInfo Properties in C# Source: https://github.com/angularsen/unitsnet/blob/master/README.md Demonstrates how to retrieve UnitInfo objects and access their properties, including the unit's enum value, names, plural names, and its representation in SI base units. ```C# // Different ways to look up the unit info. var cm = Quantity.GetUnitInfo(LengthUnit.Centimeter); if (Quantity.TryGetUnitInfo(LengthUnit.Centimeter, out UnitInfo tryGetCm)) { cm = tryGetCm; } // The unit information. cm.Value; // Enum value: LengthUnit.Centimeter cm.Name; // "Centimeter" cm.PluralName; // "Centimeters" cm.BaseUnits; // {"Length": Centimeter, "Mass": null, "Time": null, ...} ``` -------------------------------- ### Adding Official Repo as Origin Remote Source: https://github.com/angularsen/unitsnet/blob/master/Docs/collaborators/releasing-nugets.md Add the official UnitsNet repository as your 'origin' remote using either SSH or HTTPS. ```bash # Add official repo as origin remote using either SSH or HTTPS url git remote add origin git@github.com:angularsen/UnitsNet.git git remote add origin https://github.com/angularsen/UnitsNet.git ``` -------------------------------- ### Operator Overloads for Quantity Arithmetic and Construction Source: https://github.com/angularsen/unitsnet/blob/master/README.md Illustrates the use of operator overloads for performing arithmetic operations on quantities and for constructing new quantities through multiplication or division of compatible units. ```csharp // 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); Acceleration a1 = Speed.FromKilometersPerHour(80) / TimeSpan.FromSeconds(2); Acceleration a2 = Force.FromNewtons(100) / Mass.FromKilograms(20); RotationalSpeed r = Angle.FromDegrees(90) / TimeSpan.FromSeconds(2); ``` -------------------------------- ### Classic Extension Methods Syntax Source: https://github.com/angularsen/unitsnet/blob/master/README.md For C# 13 and lower, use the classic extension methods provided by UnitsNet.NumberExtensions, which require parentheses for method calls. ```csharp using UnitsNet.NumberExtensions.NumberToLength; // Classic extension methods, with parentheses Length distance = 5.Meters(); // Instead of Length.FromMeters(5) ``` -------------------------------- ### Custom Serialization for Database Storage Source: https://github.com/angularsen/unitsnet/wiki/Saving-to-database Demonstrates a custom serialization format for storing UnitsNet quantities and units in a database. This approach provides control over breaking changes by mapping units to custom string identifiers. ```csharp IQuantity myQuantity = ...; var myDbEntity = new MyDbEntity { Value = myQuantity.Value, UnitName = myQuantity switch { LengthUnit.Meter => "Length:Meter", LengthUnit.Centimeter => "Length:Centimeter", MassUnit.Kilogram => "Mass:Kilogram", // ... and any other units we want to support serializing _ => throw new NotImplementedException("Unit not supported for serialization to SQL: " + myQuantity.Unit) } }; ``` -------------------------------- ### QuantityInfo Properties in C# Source: https://github.com/angularsen/unitsnet/blob/master/README.md Illustrates how to access properties of a QuantityInfo object to retrieve details about a specific quantity, such as its name, units, base unit, dimensions, and associated types. ```C# // Different ways to look up the quantity info. QuantityInfo lengthInfo = Quantity.ByName["Length"]; lengthInfo = Length.Info; lengthInfo = Length.FromMeters(1).QuantityInfo; // The quantity information. lengthInfo.Name; // "Length" lengthInfo.UnitInfos; // UnitInfo[] for its units Centimeter, Meter, etc. lengthInfo.BaseUnitInfo; // UnitInfo for LengthUnit.Meter lengthInfo.BaseDimensions; // {"Length": 1, "Mass": 0, ...} lengthInfo.UnitType; // typeof(LengthUnit) lengthInfo.ValueType; // typeof(Length) lengthInfo.Zero; // Length.Zero ``` -------------------------------- ### Run Specific Test with .NET CLI Source: https://github.com/angularsen/unitsnet/blob/master/CLAUDE.md Runs a single, specific test case within the UnitsNet.Tests project. Use this to quickly verify a particular test. ```bash dotnet test UnitsNet.Tests --filter "FullyQualifiedName~TestClassName.TestMethodName" ``` -------------------------------- ### Construct Quantity from Value and Unit Abbreviation Source: https://github.com/angularsen/unitsnet/blob/master/README.md Create a quantity using a unit's abbreviation. This requires that the abbreviation uniquely identifies a single unit. ```csharp // Length with unit LengthUnit.Centimeter IQuantity quantity = Quantity.FromUnitAbbreviation(3, "cm"); if (Quantity.TryFromUnitAbbreviation(3, "cm", out IQuantity? quantity2)) { } ``` -------------------------------- ### Commit and Push Changes Source: https://github.com/angularsen/unitsnet/wiki/Adding-a-New-Unit Standard Git commands to stage all changes, commit them with a message, and push them to your fork. This makes your work available on your remote repository. ```sh # Do your work, stage changes, commit and push to your fork. git add -A git commit -m "My commit message" git push ``` -------------------------------- ### Adding Your Fork as 'my' Remote Source: https://github.com/angularsen/unitsnet/blob/master/Docs/collaborators/releasing-nugets.md Add your personal fork of the UnitsNet repository as a remote named 'my' using either SSH or HTTPS. ```bash # Add your fork repo as 'my' remote using either SSH or HTTPS url git remote add my git@github.com:myuser/UnitsNet.git git remote add my https://github.com/myuser/UnitsNet.git ``` -------------------------------- ### Serialize UnitsNet Quantity with Json.NET (Newtonsoft) Source: https://github.com/angularsen/unitsnet/blob/master/Docs/serialization.md Use the UnitsNet.Serialization.JsonNet library to serialize and deserialize IQuantity objects with Json.NET. Requires adding the `UnitsNetIQuantityJsonConverter` to `JsonSerializerSettings`. ```csharp var jsonSerializerSettings = new JsonSerializerSettings {Formatting = Formatting.Indented}; jsonSerializerSettings.Converters.Add(new UnitsNetIQuantityJsonConverter()); string json = JsonConvert.SerializeObject(new { Name = "Raiden", Weight = Mass.FromKilograms(90) }, jsonSerializerSettings); object obj = JsonConvert.DeserializeObject(json); ``` -------------------------------- ### Accessing Converted Values in Units.NET Source: https://context7.com/angularsen/unitsnet/llms.txt Shows how to retrieve the value of a quantity in different units using named properties or the generic .As() method. Supports conversion to other unit systems as well. ```csharp using UnitsNet; Length distance = Length.FromMeters(1.0); double cm = distance.Centimeters; // 100 double inches = distance.Inches; // 39.3701 double feet = distance.Feet; // 3.28084 double yards = distance.Yards; // 1.09361 double km = distance.Kilometers; // 0.001 double nm = distance.Nanometers; // 1_000_000_000 // Generic .As() with a unit enum value double mm = distance.As(LengthUnit.Millimeter); // 1000 // Convert to another unit system double cgsValue = distance.As(UnitSystem.CGS); // 100 (centimeters in CGS) Mass bodyWeight = Mass.FromKilograms(90); double lbs = bodyWeight.Pounds; // 198.416 double stone = bodyWeight.Stone; // 14.1728 double oz = bodyWeight.Ounces; // 3174.66 Console.WriteLine($"1 m = {cm} cm = {inches:F4} in = {feet:F4} ft"); // Output: 1 m = 100 cm = 39.3701 in = 3.2808 ft ```