Created
August 29, 2014 09:14
-
-
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
This file contains hidden or 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
class Cat
{
public string Name { get; set; }
}
var cat = new Cat { Name = "Kitty" };
var message = "Hello [Name]!".TemplifyWith(cat);