Skip to content

Instantly share code, notes, and snippets.

@imgen
Created March 12, 2020 03:35
Show Gist options
  • Save imgen/67fe186389cda6cd8eda0bb7535f31a5 to your computer and use it in GitHub Desktop.
Save imgen/67fe186389cda6cd8eda0bb7535f31a5 to your computer and use it in GitHub Desktop.
A simple named format implementation
public static string NamedFormat(string format, params object[] args)
{
var newFormat = string.Empty;
var paraIndex = 0;
var paraNameIndexMap = new Dictionary<string, int>();
for (int i = 0; i < format.Length; i++)
{
var ch = format[i];
if (ch == '{')
{
var paraName = string.Empty;
for (i++; i < format.Length; i++)
{
ch = format[i];
if (ch == '}')
{
break;
}
paraName += ch;
}
if (ch == '}')
{
if (paraNameIndexMap.ContainsKey(paraName))
{
newFormat += "{" + paraNameIndexMap[paraName] + "}";
}
else
{
newFormat += "{" + paraIndex + "}";
paraNameIndexMap[paraName] = paraIndex;
paraIndex++;
}
}
}
else
{
newFormat += ch;
}
}
if (paraIndex > args.Length)
{
throw new FormatException($"The format {format} specified more parameters than the parameters passed in");
}
return string.Format(newFormat, args);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment