What does {{{0}}} on string.Format do?

You escape a curly brace with a curly brace, i.e. {{ produces {, and }} produces }.

The {0} in the middle is interpreted as usual – i.e. a reference to parameter at index zero.

{{ {0} }}
^^ ^^^ ^^
|   |  |
|   |  +--- Closing curly brace
|   +------ Parameter reference
+---------- Opening curly brace

The end result is the value of parameter zero enclosed in curly braces:

var res = string.Format("{{{0}}}", "hello"); // produces {hello}

How is that ‘lazy’?

They call it lazy with respect to this alternative “eager” implementation:

internal class NamedObject {
    public NamedObject(string name) {
        if (String.IsNullOrEmpty(name))
            throw new ArgumentNullException(name);
        if (name[0] != '{') {
            // eagerly add {} around the name
            _name = String.Format(CultureInfo.InvariantCulture, "{{{0}}}", name);
        } else {
            _name = name;
        }
    }
    public override string ToString() {
        return _name;
    }
    string _name;
}

This implementation adds curly braces right away, even though it has no idea that the name enclosed in curly braces is going to be needed.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)