Home >Backend Development >C++ >How Can Named String Formatting Be Achieved in C#?
Python's string formatting syntax allows for formatting by name rather than position, enabling developers to use variable names directly within format strings. In C#, however, the built-in String.Format does not support this feature.
To achieve named string formatting in C#, you can implement your own method using reflection or template parsing techniques.
Using Reflection:
string myString = "{foo} is {bar} and {yadi} is {yada}".Inject(o);
Using Template Parsing:
Status.Text = "{UserName} last logged in at {LastLoginDate}".FormatWith(user);
An Improved Method:
public class FormattedString { private readonly string _template; public FormattedString(string template) { _template = template; } public string FormatWith(object o) { var type = o.GetType(); var props = type.GetProperties(); return _template.Replace("{PropertyName}", prop.GetValue(o)) .Replace("{propertyName}", prop.GetValue(o)) .ToString(); } }
Usage:
var formattedString = new FormattedString("{foo} is {bar} and {yadi} is {yada}"); Console.WriteLine(formattedString.FormatWith(new { foo = "alpha", bar = "beta", yadi = "gamma", yada = "delta" }));
With the release of C# 6 in 2015, string interpolation was introduced as a built-in feature that allows for named string formatting. The syntax resembles the custom methods discussed above:
$"{{some_variable}}: {{some_other_variable}}"
The above is the detailed content of How Can Named String Formatting Be Achieved in C#?. For more information, please follow other related articles on the PHP Chinese website!