Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / programming / string

StringFormat Methods with string keys

4.44/5 (5 votes)
17 Jan 2011CPOL1 min read 16.8K  
Presents StringFormat methods with string (not integer) keys in 'format' string.
Introduction

System.String type gives us a very useful 'Format' method, that replaces one or more format items (keys) in a specified string with the concrete values. The method determines necessary value by its position in arguments set.
So, if the format string is short or number of format items is few, we can easily control the correspondence between keys in 'format' string and values in arguments set. But if the string is too large and number of arguments is great, we can be confused in arguments order.

Body

Two methods that use names as a keys in 'format' string are presented here. If we use names as keys, and Name-Value pairs as arguments, the confusion probability is reduced.

First, we define NamedValue class that contains a name and a value of the argument.
C#
public class NamedValue {
    private string _name = "";
    public string Name {
        get { return _name; }
        set {
            if (value == null || value.Trim() == "") {
                throw new ArgumentException();
            }
            _name = value.Trim();
        }
    }
    private object _value = null;
    public object Value {
        get { return _value; }
        set { _value = value; }
    }
    public NamedValue() { }
    public NamedValue(string name, object value) {
        Name = name;
        Value = value;
    }
}

Next static class StringFormat contains methods, CreateSimpleNamedFormat and CreateNamedFormat. First argument of each method is format string, next is a set of arguments of NamedValue class, almost like in native 'Format'. The functions replace all occurrences of embraced keys in 'format' string by its values. It gets value from the property Value of correspondence NamedValue instance in arguments set.
C#
public static class StringFormat {
    /// <summary>
    /// Replaces the format item in a specified System.String with the text equivalent
    ///     of the value of a corresponding NamedValue.Value instance in a specified array.
    /// This method doesn't support modifiers.
    /// </summary>
    /// <param name="stringBuilder"></param>
    /// <param name="format">Represents formatted string, where keys are embraced names.</param>
    /// <param name="args">Arguments that replaces keys in the 'format' string.</param>
    /// <exception cref="">FormatException</exception>
    public static string CreateSimpleNamedFormat(string format, params NamedValue[] args) {
        for (int i = 0; i < args.Length; i++) {
            format = format.Replace("{" + args[i].Name + "}", args[i].Value.ToString());
        }
        return format;
    }
    /// <summary>
    /// Replaces the format item in a specified System.String with the text equivalent
    ///     of the value of a corresponding NamedValue.Value instance in a specified array.
    /// This method fully supports modifiers.
    /// </summary>
    /// <param name="stringBuilder"></param>
    /// <param name="format">Represents formatted string, where keys are embraced names with, possibly, modifiers.</param>
    /// <param name="args">Arguments that replaces keys in the 'format' string.</param>
    /// <exception cref="">FormatException</exception>
    public static string CreateNamedFormat(string format, params NamedValue[] args) {
        List<object> argsValues = new List<object>();
        for (int i = 0; i < args.Length; i++) {
            NamedValue curArg = args[i];
            format = format.Replace("{" + curArg.Name + "}", "{" + i.ToString() + "}");
            format = format.Replace("{" + curArg.Name + ":", "{" + i.ToString() + ":");
            argsValues.Add(curArg.Value);
        }
        return string.Format(format, argsValues.ToArray());
    }
}

Method 'CreateSimpleNamedFormat' doesn't support modifiers. But method 'CreateNamedFormat' fully supports it. I create two methods intentionally, because their performance differs considerably.
C# 4.0 get us the good feature of extension methods. And we can now easily realize two extension methods for StringBuilder.
C#
public static class StringBuilderExtensions {
    public static void AppendSimpleNamedFormat(this StringBuilder stringBuilder, string format, params NamedValue[] args) {
        stringBuilder.Append(StringFormat.CreateSimpleNamedFormat(format, args));
    }
    public static void AppendNamedFormat(this StringBuilder stringBuilder, string format, params NamedValue[] args) {
        stringBuilder.Append(StringFormat.CreateNamedFormat(format, args));
    }
}


Conclusion

Presented methods are very simple. It needs to perform arguments verification and some other tests. In the article, I wanted only to share my idea. I hope this article helps you in your work.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)