Created
July 24, 2018 21:09
-
-
Save nguerrera/dfd08d2ceaf38804cbcc5e60b1a48476 to your computer and use it in GitHub Desktop.
Counting placeholders
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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