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
Release: 2025-01-02 13:29:44
Original
800 people have browsed it

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);
Copy after login

Using Template Parsing:

Status.Text = "{UserName} last logged in at {LastLoginDate}".FormatWith(user);
Copy after login

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();
    }
}
Copy after login

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

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}}"
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template