Skip to content

Instantly share code, notes, and snippets.

@Logrythmik
Created July 17, 2012 22:01
Show Gist options
  • Save Logrythmik/3132447 to your computer and use it in GitHub Desktop.
Save Logrythmik/3132447 to your computer and use it in GitHub Desktop.
TemplifyWith Extension Method
public static string TemplifyWith<T>(this string templatedString, T obj, string tokenFormat = "[{0}]")
{
var result = templatedString;
var type = typeof(T);
foreach (var propertyInfo in type.GetProperties())
{
var token = string.Format(tokenFormat, propertyInfo.Name);
var propType = propertyInfo.PropertyType;
if (propType.IsValueType || propType == typeof(string))
{
try
{
var value = propertyInfo.GetValue(obj, null);
if (value != null)
result = result.Replace(token, value.ToString());
}
catch (Exception) { /* Do nothing */ }
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment