views:

510

answers:

3

Is it possible to specify some kind of flag or modifier to a string format param to customize it, something like the number formating flags?

Example of want I want:

String.Format("Hi {0:touppercase}, you have {1} {2:tolowercase}.", "John", 6, "Apples");

Wanted output: Hi JOHN, you have 6 apples.

PS: Yes I know that I can change the case of the param before using it on the string format but I don't want this.

+2  A: 

In short, no; AFAIK you'd have to fix the source values, or use your own replacement to string.Format. Note that if you are passing in a custom culture (to string.Format) you may want to use culture.TextInfo.ToLower(s), rather than just s.ToLower().

Marc Gravell
I was just going to suggest writing your own string formatter.
ChrisF
Indeed - you could probably *start* here: http://stackoverflow.com/questions/1322037#1322103, but lots more to do...
Marc Gravell
+2  A: 

No, but you can vote for it on Microsoft Connect, and maybe it will be in a future version of the Framework.

Joe
+3  A: 

There's only padding and allignment formating... So the easy way is like you said, use "John".ToUpper() or "John".ToLower().

Another solution could be create a custom IFormatProvider, to provide the string format you want.

This is how will look the IFormatProvider and the string.Format call.

public class CustomStringFormat : IFormatProvider, ICustomFormatter
{
    public object GetFormat(Type formatType)
    {
        if (formatType == typeof(ICustomFormatter))
            return this;
        else
            return null;

    }

    public string Format(string format, object arg, IFormatProvider formatProvider)
    {
        string result = arg.ToString();

        switch (format.ToUpper())
        {
            case "U": return result.ToUpper();
            case "L": return result.ToLower();
            //more custom formats
            default: return result;
        }
    }
}

And the call will look like: string.Format(new CustomStringFormat(), "Hi {0:U}", "John");

MF