Skip to content

Instantly share code, notes, and snippets.

@ryanlewis
Last active August 31, 2016 08:14
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 ryanlewis/ad28c52bc31aa5e32647 to your computer and use it in GitHub Desktop.
Save ryanlewis/ad28c52bc31aa5e32647 to your computer and use it in GitHub Desktop.
.FormatWith() extension method that we use with some of our Umbraco sites
using System;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
namespace MyUmbracoSite.Core.Extensions
{
public static class StringExtensions
{
// http://bendetat.com/the-greatest-string-formatwith-implementation-in-the-world.html
public static string FormatWith(this string format, params object[] args)
{
if (format == String.Empty) return format;
args = args ?? new object[0];
string result;
var numberedTemplateCount = (from object match in new Regex(@"\{\d{1,2}\}").Matches(format) select match.ToString()).Distinct().Count();
if (numberedTemplateCount != args.Length)
{
var argsDictionary = args[0].ToDictionary();
if (!argsDictionary.Any())
{
throw new InvalidOperationException("Please supply enough args for the numbered templates or use an anonymous object to identify the templates by name.");
}
result = argsDictionary.Aggregate(format, (current, o) => current.Replace("{" + o.Key + "}", (o.Value ?? string.Empty).ToString()));
}
else
{
result = string.Format(format, args);
}
if (result == format && result.Contains("{"))
{
throw new InvalidOperationException("You cannot mix template types. Use numbered templates or named ones with an anonymous object.");
}
return result;
}
}
}
@ryanlewis
Copy link
Author

"This string is {foo}".FormatWith(new { foo = "bar" };
// returns "This string is bar"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment