Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
.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

This comment has been minimized.

Copy link
Owner Author

@ryanlewis ryanlewis commented Aug 31, 2016

"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