Skip to content

UnitParser: adding overloads for getting a UnitInfo using a type/name and abbreviation#1585

Merged
angularsen merged 2 commits into
angularsen:masterfrom
lipchev:unit-parser-get-unit-from-abbreviation
Jul 27, 2025
Merged

UnitParser: adding overloads for getting a UnitInfo using a type/name and abbreviation#1585
angularsen merged 2 commits into
angularsen:masterfrom
lipchev:unit-parser-get-unit-from-abbreviation

Conversation

@lipchev
Copy link
Copy Markdown
Collaborator

@lipchev lipchev commented Jul 26, 2025

Adding the following (public) methods to the UnitParser

  • UnitInfo GetUnitFromAbbreviation(string quantityName, string unitAbbreviation, IFormatProvider? formatProvider)
  • UnitInfo GetUnitFromAbbreviation(Type quantityType, string unitAbbreviation, IFormatProvider? formatProvider)
  • bool TryGetUnitFromAbbreviation(string quantityName, string? unitAbbreviation, IFormatProvider? formatProvider, [NotNullWhen(true)] out UnitInfo? unitInfo)
  • bool TryGetUnitFromAbbreviation(Type quantityType, string? unitAbbreviation, IFormatProvider? formatProvider, [NotNullWhen(true)] out UnitInfo? unitInfo)

@lipchev
Copy link
Copy Markdown
Collaborator Author

lipchev commented Jul 26, 2025

I'm currently using the getters in the AbbreviatedUnitsConverter of the 🐲 project:

            UnitInfo unitInfo;
            if (quantityName != null && unitAbbreviation != null)
            {
                unitInfo = _unitParser.GetUnitFromAbbreviation(quantityName, unitAbbreviation, serializer.Culture);
            }
            else if (unitAbbreviation != null)
            {
                unitInfo = objectType == typeof(IQuantity)
                    ? _unitParser.GetUnitFromAbbreviation(unitAbbreviation, serializer.Culture)
                    : _unitParser.GetUnitFromAbbreviation(Nullable.GetUnderlyingType(objectType) ?? objectType, unitAbbreviation, serializer.Culture);
            }
            else if (quantityName != null)
            {
                unitInfo = _unitParser.Quantities.GetQuantityByName(quantityName).BaseUnitInfo;
            }
            else if (objectType != typeof(IQuantity))
            {
                unitInfo = _unitParser.Quantities.GetQuantityInfo(Nullable.GetUnderlyingType(objectType) ?? objectType).BaseUnitInfo;
            }
            else
            {
                throw new FormatException("The target unit cannot be determined from the provided JSON.");
            }

Technically, if we wanted to- we could make add the serialization project as InternalsVisibleTo and we wouldn't need these at all, but I don't know- might be useful.

@angularsen angularsen merged commit 3e7a6fd into angularsen:master Jul 27, 2025
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants