Getting values into a string

There are often times where it’s necessary to have some sort of template in a string, with placeholders that will be replaced with data-driven values at runtime.  Examples of this include email templates, mail merges and even integration scenarios.  Now there are many sophisticated and complex approaches to solving this problem, but here is a simple approach that works:

public static class StringExtensions
{
    public static string AddTokens(this string message, object tokenValues)
    {
        return tokenValues.GetType()
                .GetProperties()
                .Select(property => new
                            {
                                Key = property.Name,
                                Value = property.GetValue(tokenValues, new object[0]) as string
                            })
                .Aggregate(message, (current, token) => current.Replace("{" + token.Key + "}", token.Value));

    }

}

And to show you how to use it:

[Test]
public void ShouldReplaceTokens()
{
    var result = "1234{numbers}890".AddTokens(new { numbers = "567" });
    Assert.AreEqual("1234567890", result, "Tokens not added correctly");
}

January 17 2012
Comments are closed