Currently I am doing this:
I have text that looks like:
Hello ${user.name}, this is ....
And I do this:
public string TransformUser(User user, string text)
{
StringBuilder sb = new StringBuilder(text);
sb.Replace("${user.name}", user.Name);
...
...
return sb.ToString();
}
Is there a better way, maybe using reflection somehow to loop through the classes public properties?
Edit
Would it be possible to make this method Generic, so I can pass any object to it?
Looping through all properties using reflection and replacing the keys in the string would look roughly like this:
It uses
CanReadto check if the property has getter and then invokes the getter to read the value. A value is converted to string simply usingToStringwhich will probably work for primitive types (depending on the required behavior). This is case sensitive, so you may want to useToLowerif the users write keys using lowercase (as in your example).