Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

Custom formatting in .NET: provider, formatter, and the value's own type

Distinguish three formatting contracts: looking up a service, intercepting a format item, and letting the value's own type produce the text.

Version: C# 12 and .NET 8; later runtimes may add compatible features

Syntax

C# 12 / .NET 8, namespace System
IFormatProvider: object? GetFormat(Type? formatType);
ICustomFormatter: string Format(string? format, object? arg, IFormatProvider? formatProvider);
IFormattable: string ToString(string? format, IFormatProvider? formatProvider);
Composite formatting: string.Format(provider, "{0:code}", value)
Direct call: ((IFormattable)value).ToString("G", provider)

In C# 12 and .NET 8, all three interfaces are in System. The provider-taking overload of string.Format calls IFormatProvider.GetFormat(Type?) with typeof(ICustomFormatter), not the type of the value being formatted. The provider returns a service of the requested type or null; it can return this if it implements the service itself. The formatter found by this lookup is reused within that call.

For {0:F2}, ICustomFormatter.Format receives "F2", the argument at index zero, and the provider. For {0}, the format code is absent, so the method receives null. Any string result, even "", handles the item. A null result tells this string.Format overload to continue with ordinary formatting. The ! in null! only suppresses a nullable warning: the method still returns null even though its return type is string.

If there is no custom formatter or it declines the item, string.Format in .NET 8 can first try ISpanFormattable.TryFormat. If that step is skipped or TryFormat returns false, a non-null argument that implements IFormattable is formatted through IFormattable.ToString(format, provider). For other non-null arguments, parameterless ToString() is used and receives no format code. A null argument that reaches ordinary formatting is treated as an empty string before any alignment padding. Implement "G" and null as general formatting. A type can throw FormatException for an unsupported code; string.Format can independently throw the same exception for an item index outside the argument list.

Calling the two-argument ToString directly does not automatically invoke ICustomFormatter. The type can still use the provider, for example to look up NumberFormatInfo or DateTimeFormatInfo through GetFormat. Avoid calling string.Format again inside Format with the same provider, argument, and code: it can re-enter the same formatter.

Examples

#nullable enable
using System;
using System.Globalization;

var provider = new ReadingFormatProvider();
var reading = new Voltage(12.5m);
Console.WriteLine(string.Format(provider, "{0:bracket} | {0:F2} | {0}", reading));

sealed class ReadingFormatProvider : IFormatProvider, ICustomFormatter
{
    public object? GetFormat(Type? formatType) =>
        formatType == typeof(ICustomFormatter)
            ? this
            : CultureInfo.InvariantCulture.GetFormat(formatType);

    public string Format(string? format, object? arg, IFormatProvider? formatProvider)
    {
        if (format == "bracket" && arg is Voltage voltage)
            return "[" + voltage.ToString("F2", formatProvider) + "]";

        return null!; // string.Format continues with ordinary formatting.
    }
}

sealed class Voltage(decimal volts) : IFormattable
{
    public override string ToString() => ToString("G", null);

    public string ToString(string? format, IFormatProvider? formatProvider) =>
        (format switch
        {
            null or "G" => volts.ToString("G", formatProvider),
            "F2" => volts.ToString("F2", formatProvider),
            _ => throw new FormatException($"Unsupported voltage format: {format}")
        }) + " V";
}

Result

[12.50 V] | 12.50 V | 12.5 V

The formatter handles `bracket` for `Voltage` by calling `ToString("F2", formatProvider)` directly and adding square brackets. The other two items fall back to `Voltage.ToString`. The provider delegates culture-data requests to `CultureInfo.InvariantCulture`, so the decimal separator is a period.

Related lessons

  • C# · Lesson 33 · Advanced · Version: 3

Sources