Skip to content

Custom abbreviation doesn't ToString() well #577

Closed
@gregsdennis

Description

@gregsdennis

Problem

If I add a custom abbreviation:

UnitAbbreviationsCache.Default.MapUnitToAbbreviation(VolumeUnit.UsCustomaryCup, "Cup");

it parses just fine. However, when I call .ToString(), I still get the default abbreviation of "".

NOTE I understand that there is ambiguity between "cup" units, and that's why it's defaulted to an empty string. I'm using the code above to override this default and use US Customary Cup for my app.

Cause

The above method merely appends the abbreviation to the list of acceptable values.

internal void Add(int unit, string abbreviation)
{
if(!unitToAbbreviationMap.TryGetValue(unit, out var abbreviationsForUnit))
abbreviationsForUnit = unitToAbbreviationMap[unit] = new List<string>();
if(!abbreviationToUnitMap.TryGetValue(abbreviation, out var unitsForAbbreviation))
abbreviationToUnitMap[abbreviation] = unitsForAbbreviation = new List<int>();
abbreviationsForUnit.Add(abbreviation);
unitsForAbbreviation.Add(unit);
}

However, the .ToString() methods on classes only use the first abbreviation in the list.

return abbreviations.First();

Proposal

Add a new method

void MapUnitToDefaultAbbreviation<TUnitType>(TUnitType unit, string abbreviation) where TUnitType : Enum
{
     ...
}

that would insert the new abbreviation at the beginning of the list rather than appending it to the end. Then when .ToString() is called, it can still take the first abbreviation.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions