Skip to content

Instantly share code, notes, and snippets.

@pmunin
Created March 4, 2019 21:31
Show Gist options
  • Select an option

  • Save pmunin/5e3057cbaf70954d89545ebcc80e5ee1 to your computer and use it in GitHub Desktop.

Select an option

Save pmunin/5e3057cbaf70954d89545ebcc80e5ee1 to your computer and use it in GitHub Desktop.

Revisions

  1. pmunin created this gist Mar 4, 2019.
    43 changes: 43 additions & 0 deletions FormattableStringExtensions.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.CompilerServices;
    using System.Threading.Tasks;

    public static class FormattableStringExtensions
    {
    public static FormattableString AsFormattable(this string str) {
    return FormattableStringFactory.Create(str);
    }

    class FormattablePlaceholder : IFormattable
    {
    public Func<string, IFormatProvider, string> ValueByFormat { get; set; }
    public string ToString(string format, IFormatProvider formatProvider)
    {
    return ValueByFormat(format, formatProvider);
    }
    }


    public static FormattableString Join(string separator, params FormattableString[] strings)
    {
    var iArg = 0;
    var formats = strings.Select(str =>
    {
    var args = Enumerable.Range(iArg, str.ArgumentCount).ToArray();
    iArg += str.ArgumentCount;
    return string.Format(str.Format, args: args.Select(arg=> new FormattablePlaceholder() {
    ValueByFormat = (fmt, fp) => fmt != null ? $"{{{arg}}}:{fmt}}}" : $"{{{arg}}}"
    }).ToArray());
    }).ToArray();

    return FormattableStringFactory.Create(string.Join(separator, value:formats), arguments: strings.SelectMany(s => s.GetArguments()).ToArray());
    }

    public static FormattableString Add(this FormattableString formattable, params FormattableString[] strings)
    {
    strings = new[] { formattable }.Concat(strings).ToArray();
    return Join(string.Empty,strings);
    }
    }