50

Is it possible to specify some kind of flag or modifier on a string format param to make it lower case or upper case?

Example of what 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 in the string format, but I don't want this.

Frank Tan
  • 4,234
  • 2
  • 19
  • 29
rjlopes
  • 2,430
  • 4
  • 21
  • 23
  • 4
    I know you don't want it, but I can't see why just calling .tolower() or .toupper() on the string params is a problem. – tjmoore Dec 03 '09 at 12:46
  • 6
    " I can't see why just calling .tolower() or .toupper() on the string params is a problem" - for example, data binding. – Joe Dec 04 '09 at 20:02
  • I've got the same situation. The reason .ToLower() won't work for me is that the formatting string is coming from a database (ie, it's configurable by the end user). – Ryan May 14 '12 at 20:15

2 Answers2

74

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?.ToUpperInvariant()) // culture independent
        {
            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");
Sedat Kapanoglu
  • 46,641
  • 25
  • 114
  • 148
Guido Zanon
  • 2,939
  • 26
  • 31
  • 1
    Is there any way of doing this within the confines of a DisplayFormatAttribute? – howcheng Jul 28 '14 at 17:11
  • 1
    If format is not specified there will be `NullReferenceException`, so null check condition in `Format()` method should be added. – gabr Jan 21 '16 at 13:37
8

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
  • 1,026,079
  • 266
  • 2,566
  • 2,900