Skip to content

Overrides of unit abbreviations in non-default cultures causes Quantity.Parse to fail #832

Closed
@hemenwaynick

Description

@hemenwaynick

Describe the bug
UnitsNet offers a public method that allows consumers of the NuGet package to override the default abbreviations used for different units.

For example, one can write

UnitAbbreviationsCache.Default.MapUnitToDefaultAbbreviation(typeof(MassFlowUnit), (int)MassFlowUnit.GramPerSecond, CultureInfo.CurrentCulture, "grams/second")

in order to use "grams/second" instead of "g/s" as the displayed abbreviation.

However, if the current culture is something other than en-US, some problems arise when attempting to call

UnitsNet.Quantity.Parse(Type quantityType, string quantityString)

after performing the above override.

If we had an override as in the example above, attempting to parse any mass flow string that doesn't use the "grams/second" abbreviation would fail in a non-English culture.

For example,

Quantity.Parse(typeof(MassFlow), "10 lb/s")

would fail if the current culture were de-DE.

To Reproduce
(1) Add an override similar to the one in the description, using a culture other than en-US.
(2) Call Quantity.Parse in the culture that was used specified in your override, and make this call on a quantity string that uses a unit abbreviation other than the one you specified in the override.
The parse should fail.
(Bug was found in UnitsNet 4.65.0 but hasn't been fixed to my knowledge.)

Expected behavior
Calls to Quantity.Parse that succeed without overrides to unit abbreviations should behave the same way with overrides.
Without overrides, UnitsNet falls back to using en-US for non-English cultures (in most cases). The override is causing UnitsNet to ignore the fallback abbreviations.

Screenshots
The problem appears to lie in how the following method in UnitAbbreviationsCache.cs is handled. A return value of true is given even when the lookup that ends up getting stored in unitToAbbreviations may not include any abbreviations other than ones that have been specified in an override. At other points in this file, a true return value from TryGetUnitValueAbbreviationLookup will cause UnitsNet to use the incomplete lookup and ignore the fallback culture.
image

Additional context
I encountered this bug when overriding unit abbreviations, but it would seem to apply also to cases where one simply adds new abbreviations as well.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions