Skip to content

How Formatters Work

axunonb edited this page Mar 3, 2022 · 1 revision

What Are Formatters For

While source extensions translate complex types into objects, which can be represented as a string, formatters determine the way these objects are output.

Register Formatters

Formatters are added by calling

  • SmartFormatter.AddExtensions(...)
  • SmartFormatter.InsertExtension(...)

With AddExtensions(...) all WellKnownExtensionTypes.Sources and WellKnownExtensionTypes.Formatters are automatically inserted to the extension list at the place where they usually should be.

InsertExtension(...) lets you insert an extension to the desired position in the list.

// Add needed source extensions
var smart = new SmartFormatter()
    // Add source extensions
    .AddExtensions(new ReflectionSource(), new DefaultSource())
    // Add formatter extensions
    .AddExtensions(new ListFormatter(), new DefaultFormatter);

// Add all default source and formatter extensions
smart = Smart.CreateDefaultFormatter();

From a performance perspective, only register formatter extensions that are actually needed.

How Formatters Can Be Selected

Different formatters may be able to format the same object type (e.g. null). Some formatters have property CanAutoDetect = true, meaning they can find out whether they can process the format. That's why the order in the list of registered formatters is important.

Example:

The ConditionalFormatter can be invoked explicitly and with auto-detection:

// Include the name of the formatter
Smart.Format("{0:cond:{}|Empty}", "Hello");

// Rely on the CanAutoDetect feature
Smart.Format("{0:{}|Empty}", "Hello");

The recommendation, is to always include the (optional) formatter name in the format.

Clone this wiki locally