Skip to content

Commit 42e8019

Browse files
authored
README: Dynamic parsing examples
1 parent ff32edc commit 42e8019

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

README.md

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,14 +119,29 @@ Unfortunately there is no built-in way to avoid this, either you need to ensure
119119
Example:
120120
`Length.Parse("1 pt")` throws `AmbiguousUnitParseException` with message `Cannot parse "pt" since it could be either of these: DtpPoint, PrinterPoint`.
121121

122-
### Dynamically Parsing Quantities and Units
122+
### Dynamically Parsing and Converting Quantities
123123
Sometimes you need to work with quantities and units at runtime, such as parsing user input.
124124
There are three classes to help with this:
125+
- [UnitParser]() for parsing unit abbreviation strings like `cm` to `LengthUnit.Centimeter`
126+
- [UnitAbbreviationsCache]() for looking up unit abbreviations like `cm` given type `LengthUnit` and value `1` (`Centimeter`)
127+
- [UnitConverter]() for converting values given a quantity name `Length`, a value `1` and from/to unit names `Centimeter` and `Meter`
125128

126129
```c#
130+
// This type was perhaps selected by the user in GUI from a list of units
131+
Type lengthUnitType = typeof(LengthUnit); // Selected by user in GUI from a list of units
127132
133+
// Parse units dynamically
134+
UnitParser parser = UnitParser.Default;
135+
int fromUnitValue = (int)parser.Parse("cm", lengthUnitType); // LengthUnit.Centimeter == 1
136+
137+
// Get unit abbreviations dynamically
138+
var cache = UnitAbbreviationsCache.Default;
139+
string fromUnitAbbreviation = cache.GetDefaultAbbreviation(lengthUnitType, 1); // "cm"
140+
141+
double centimeters = UnitConverter.ConvertByName(1, "Length", "Meter", "Centimeter"); // 100
128142
```
129143

144+
For more examples on dynamic parsing and conversion, see the unit conversion applications below.
130145

131146
### <a name="example-app"></a>Example: Creating a dynamic unit converter app
132147
[Source code](https://github.com/angularsen/UnitsNet/tree/master/Samples/UnitConverter.Wpf) for `Samples/UnitConverter.Wpf`<br/>

0 commit comments

Comments
 (0)