C# string format flag or modifier to lowercase param
Asked Answered
A

3

52

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.

Ares answered 3/12, 2009 at 12:41 Comment(3)
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.Narbada
" I can't see why just calling .tolower() or .toupper() on the string params is a problem" - for example, data binding.Cockfight
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).Murk
R
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");
Radmilla answered 3/12, 2009 at 13:19 Comment(2)
Is there any way of doing this within the confines of a DisplayFormatAttribute?Roxannaroxanne
If format is not specified there will be NullReferenceException, so null check condition in Format() method should be added.Monomolecular
O
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().

Orren answered 3/12, 2009 at 12:45 Comment(2)
I was just going to suggest writing your own string formatter.Darwindarwinian
Indeed - you could probably start here: stackoverflow.com/questions/1322037#1322103, but lots more to do...Orren
F
0

I stumbled upon this question trying to solve the same exact problem but with the difference the values being formatted were coming from Enums so I came up with a generic enough implementation that could be used for any type and dynamically invoked any string class method (such as ToLower or ToUpper but could be used for other methods too).

Of course one could implement IFormattable on the class they wish to format but in the case of string and Enum that is not possible so I created a wrapper class:

public class Formattable<T> : IFormattable
{
    private T obj;

    public Formattable(T obj)
    {
        this.obj = obj;
    }

    public string ToString(string format, IFormatProvider formatProvider)
    {
        var formatted = obj.ToString();

        if (string.IsNullOrEmpty(format)) return formatted;

        var method = typeof(string).GetMethod(format, new Type[0]);

        return (string)method.Invoke(formatted, new object[0]);
    }
}

public static class FormattableExtension
{
    public static Formattable<T> Formattable<T>(this T o)
    {
        return new Formattable<T>(o);
    }
}

You then can use this while formatting your parameters like:

String.Format(
  "This will make {0:ToLower} lowercase while {0:ToUpper} uppercase", 
  obj.Formattable()
);
Fielder answered 20/9, 2023 at 0:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.