Home >Backend Development >C++ >How Can Named String Formatting Be Achieved in C#?

How Can Named String Formatting Be Achieved in C#?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-02 13:29:44798browse

How Can Named String Formatting Be Achieved in C#?

Named String Formatting 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.

Custom Solutions

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" }));

String Interpolation (C# 6 and later)

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn