PluralFormatter.cs 1.1 KB

12345678910111213141516171819202122232425262728293031323334
  1. using System;
  2. using static System.String;
  3. namespace Quadarax.Foundation.Core.Value.Formatters
  4. {
  5. /// <summary>
  6. /// Formats a numeric value based on a format P:Plural:Singular
  7. /// </summary>
  8. public class PluralFormatter : ICustomFormatter, IFormatProvider
  9. {
  10. public string Format(string? format, object? arg, IFormatProvider? formatProvider)
  11. {
  12. if (arg !=null)
  13. {
  14. var parts = format == null ? Array.Empty<string>() : format.Split(':'); // ["P", "Plural", "Singular"]
  15. if (parts[0] == "P") // correct format?
  16. {
  17. // which index position to use
  18. int partIndex = (arg.ToString() == "1")?2:1;
  19. // pick string (safe guard for array bounds) and format
  20. return $"{arg} {(parts.Length > partIndex ? parts[partIndex] : "")}";
  21. }
  22. }
  23. return String.Format(format ?? string.Empty, arg);
  24. }
  25. public object? GetFormat(Type? formatType)
  26. {
  27. return formatType == typeof(ICustomFormatter)?this:null;
  28. }
  29. }
  30. }