Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

ICustomFormatter.Format — custom value formatting

ICustomFormatter.Format lets a format provider control a value's text representation without changing its type. It works with IFormatProvider and methods such as string.Format; an implementation should also handle ordinary formats and null.

Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification

Syntax

string Format(string? format, object? arg, IFormatProvider? formatProvider);

ICustomFormatter.Format in the System namespace is a callback used by custom formatting. Unlike IFormattable, which the formatted type implements, it lets you define rules outside that type. The API is available in .NET 10; it is neither new to that version nor a feature requiring LangVersion=preview.

Pass an IFormatProvider to string.Format or StringBuilder.AppendFormat. The mechanism asks GetFormat(typeof(ICustomFormatter)) for a formatter. One class can implement both interfaces and return this. Format is then called for each format item: for {0:tag}, it receives "tag" as format, and arg is the argument at index 0. Without a specifier, format is null; formatProvider identifies the formatting service provider.

Handle your custom type-and-format combinations, then delegate other cases to IFormattable.ToString(format, provider) or parameterless ToString(). Return an empty string for arg == null. An invalid format passed through to fallback formatting may cause FormatException; a custom formatter should not blindly hide that error.

The example recognizes "tag" only for int. For other values, it explicitly uses CultureInfo.InvariantCulture rather than relying on the current culture or the formatProvider parameter. Consequently, F2 produces 12.50, and null leaves empty brackets.

Examples

#nullable enable
using System;
using System.Globalization;

Console.WriteLine(string.Format(new LabelFormatter(),
    "{0:tag} | {1:F2} | [{2}]", 42, 12.5m, (object?)null));

sealed class LabelFormatter : IFormatProvider, ICustomFormatter
{
    public object? GetFormat(Type? formatType) =>
        formatType == typeof(ICustomFormatter) ? this : null;

    public string Format(string? format, object? arg,
        IFormatProvider? formatProvider)
    {
        if (format == "tag" && arg is int number)
            return "ID-" + number.ToString("D4", CultureInfo.InvariantCulture);

        return arg switch
        {
            null => string.Empty,
            IFormattable formattable =>
                formattable.ToString(format, CultureInfo.InvariantCulture) ?? string.Empty,
            _ => arg.ToString() ?? string.Empty
        };
    }
}

Result

ID-0042 | 12.50 | []

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources