Does .NET 3.5 C# allow us to include a variable within a string variable without having to use the + concatenator (or string.Format(), for that matter).
For example (In
Based on the great answer of @JesperPalm I found another interesting solution which let's you use a similar syntax like in the normal string.Format
method:
public static class StringExtensions
{
public static string Replace(this string text, T values)
{
var sb = new StringBuilder(text);
var properties = typeof(T)
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.ToArray();
var args = properties
.Select(p => p.GetValue(values, null))
.ToArray();
for (var i = 0; i < properties.Length; i++)
{
var oldValue = string.Format("{{{0}", properties[i].Name);
var newValue = string.Format("{{{0}", i);
sb.Replace(oldValue, newValue);
}
var format = sb.ToString();
return string.Format(format, args);
}
}
This gives you the possibility to add the usual formatting:
var hello = "Good morning";
var world = "Mr. Doe";
var s = "{hello} {world}! It is {Now:HH:mm}."
.Replace(new { hello, world, DateTime.Now });
Console.WriteLine(s); // -> Good morning Mr. Doe! It is 13:54.