Custom IFormatProvider for encodingURL data

This is an old post, but still very valuable. A method to use IFormatProvider (string interpolation/String.Format()) to encode data for a url.

class UrlFormatProvider : IFormatProvider
{
  private readonly UrlFormatter _formatter = new UrlFormatter();

  public object GetFormat(Type formatType)
  {
    if (formatType == typeof(ICustomFormatter))
      return _formatter;
    return null;
  }

  class UrlFormatter : ICustomFormatter
  {
    public string Format(string format, object arg, IFormatProvider formatProvider)
    {
      if (arg == null)
        return string.Empty;
      if (format == "r")
        return arg.ToString();
      return Uri.EscapeDataString(arg.ToString());
    }
  }
}

Blog: http://www.thomaslevesque.com/2015/02/24/customizing-string-interpolation-in-c-6/
Code: https://github.com/thomaslevesque/blog-code-samples/blob/master/TestStringInterpolation/TestStringInterpolation/UrlFormatProvider.cs