Skip to content

Default _ DefaultFormatter

axunonb edited this page Mar 30, 2022 · 8 revisions

The DefaultFormatter takes care of the default formatting, pretty much with the same logic as string.Format.

In particular, it is required for

  • output of nested Placedholders (going beyond string.Format capabilities)
  • output, when IFormatProvider with ICustomFormatter is in place as an argument to SmartFormatter.Format(...)
  • output of any arguments implementing IFormattable
  • output of string variables
  • output of any object (in which case its .ToString() method is invoked)

Syntax Details

{ Any Value : d : format }

Value formatter name format
Any value "d" or implicit optional: format to use

Configuration:

string Name: default is d
The name to use a named formatter

Examples

Simple invokation of DefaultFormatter

// implicit invokation
Smart.Format("{0}", 1234);
// explicit invokation by formatter name
Smart.Format("{0:d}", 1234);
// with CultureInfo
Smart.Format(CultureInfo.GetCultureInfo("en-US"), "{0:d}", 1234);
// all output: "1234"

Argument implementing IFormattable

// A simple class
public class FmtDemo : IFormattable
{
   public string ToString(string? format, IFormatProvider? p)
   {
      return $"{format} implmenting IFormattable";
   }
}

Smart.Format("{0:FmtDemo}", new FmtDemo());
// Outputs: "FmtDemo implementing IFormattable"

Using a FormatDelegate

var amount = 123.456M;
var c = new System.Globalization.CultureInfo("fr-FR");
// Only works for indexed placeholders
var formatDelegate = new SmartFormat.Utilities.FormatDelegate((format, culture) => $"{format}: {amount.ToString(c)}");
Smart.Format("{0:The amount is}", formatDelegate);
// Outputs: "The amount is: 123,456"

With Custom IFormatProvider and ICustomFormatter

public class ReverseFormatProvider : IFormatProvider
{
    public object GetFormat(Type? formatType)
    {
        if (formatType == typeof(ICustomFormatter)) return new ReverseFormatAndArgumentFormatter();
        
        return new object();
    }
}

public class ReverseFormatAndArgumentFormatter : ICustomFormatter
{
    public string Format(string? format, object? arg, IFormatProvider? formatProvider)
    {
        return new string(format!.Reverse().Select(c => c).ToArray()) + ": " +
               new string((arg as string ?? "?").Reverse().Select(c => c).ToArray());
    }
}

Use the custom IFormatProvider:

// only these 2 extensions are needed
var smart = new SmartFormatter()
    .AddExtensions(new DefaultFormatter())
    .AddExtensions(new DefaultSource());

smart.Format(new ReverseFormatProvider(), "0:format", "value");
// Outputs: "tamrof: eulav"
// (value and format arguments reversed)
Clone this wiki locally