Skip to content

Instantly share code, notes, and snippets.

@nguerrera
Created July 24, 2018 21:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nguerrera/dfd08d2ceaf38804cbcc5e60b1a48476 to your computer and use it in GitHub Desktop.
Save nguerrera/dfd08d2ceaf38804cbcc5e60b1a48476 to your computer and use it in GitHub Desktop.
Counting placeholders
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(CountPlaceholders("{0,3} {1:x} {{2}}"));
}
static int CountPlaceholders(string format)
{
var counter = new CountingFormatter();
string.Format(counter, format, s_enoughArgs);
return counter.PlaceholderCount;
}
private static readonly object[] s_enoughArgs = new object[99];
private sealed class CountingFormatter : ICustomFormatter, IFormatProvider
{
public int PlaceholderCount;
public string Format(string format, object arg, IFormatProvider formatProvider)
{
PlaceholderCount++;
return "";
}
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
{
return this;
}
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment