Created
July 17, 2012 22:01
-
-
Save Logrythmik/3132447 to your computer and use it in GitHub Desktop.
TemplifyWith Extension Method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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