Skip to content

Instantly share code, notes, and snippets.

@KillerGoldFisch
Created November 16, 2017 16:04
Show Gist options
  • Save KillerGoldFisch/0d2265072a124b4ee238626e174e7812 to your computer and use it in GitHub Desktop.
Save KillerGoldFisch/0d2265072a124b4ee238626e174e7812 to your computer and use it in GitHub Desktop.
Runtime String interpolation for .NET Core
public static string Interpolate(string value, System.Collections.Generic.IDictionary<string, object> inject) {
return System.Text.RegularExpressions.Regex.Replace(value, @"{(?<exp>[^}]+)}", match => {
var p = inject.Select(pair => System.Linq.Expressions.Expression.Parameter(pair.Value.GetType(), pair.Key));
var e = System.Linq.Dynamic.Core.DynamicExpressionParser.ParseLambda(p.ToArray(), null, match.Groups["exp"].Value, inject.Values.ToArray());
return (e.Compile().DynamicInvoke(inject.Values.ToArray()) ?? "").ToString();
});
}
/*
Dependencys:
* System.Linq.Dynamic.Core
Example:
Console.WriteLine(Interpolate("{x.Name} {y.Value}", new Dictionary<string, object> {
{
"x", new { Name = "Hello" }
},
{
"y", new { Value = "World" }
}
}));
*/
@alirizaadiyahsi
Copy link

This is perfect and clean solution. Thanks a lot.

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