Skip to content

Instantly share code, notes, and snippets.

@valerysntx
Created August 29, 2014 09: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 valerysntx/d3b68ee3432dcf7a5587 to your computer and use it in GitHub Desktop.
Save valerysntx/d3b68ee3432dcf7a5587 to your computer and use it in GitHub Desktop.
String extension method for class-based token replacement on strings, using reflection on class properties
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;
}
@valerysntx
Copy link
Author

class Cat
{
public string Name { get; set; }
}
var cat = new Cat { Name = "Kitty" };
var message = "Hello [Name]!".TemplifyWith(cat);

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