views:

389

answers:

4

Is there a way to String.Format a message without having to specify {1}, {2}, etc? Is it possible to have some form of auto-increment? (Similar to plain old printf)

+1  A: 

Afraid not -- where would it put the objects into the string? Using printf, you still need to put specifiers in somewhere.

mquander
Yes, I don't mind using specifiers, but I don't want to hard-code the indices.
Hosam Aly
@Hosam - is this for the purpose of embedding other formattable strings within formattable strings and then adding all the params at a later stage?
BenAlabaster
@balabaster: no, it's one call to `String.Format` to insert a few variables.
Hosam Aly
+2  A: 

You can use a named string formatting solution, which may solve your problems.

cbp
Thank you. It's nice to know about it.
Hosam Aly
+1  A: 

There is a C# implementation of printf available here

Rune Grimstad
A: 

One could always use this (untested) method, but I feel it's over complex:

public static string Format(char splitChar, string format,
                            params object[] args)
{
    string splitStr = splitChar.ToString();
    StringBuilder str = new StringBuilder(format + args.Length * 2);
    for (int i = 0; i < str.Length; ++i)
    {
        if (str[i] == splitChar)
        {
            string index = "{" + i + "}";
            str.Replace(splitStr, index, i, 1);
            i += index.Length - 1;
        }
    }

    return String.Format(str.ToString(), args);
}
Hosam Aly