CKTIS / C#
IFormattable — formatting values with a format provider
System.IFormattable defines conversion of a value to text using a format string and a provider of formatting information. It lets custom types participate in composite formatting, such as string.Format, rather than relying only on parameterless ToString().
Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification
Syntax
public interface IFormattable
{
string ToString(string? format, IFormatProvider? formatProvider);
}System.IFormattable contains one method: IFormattable.ToString(string? format, IFormatProvider? formatProvider). The format parameter selects the value's representation, while formatProvider supplies formatting information, such as the decimal separator. This is a library contract available in .NET 10, not a feature requiring preview C#.
An implementation must support "G" (general format) and null for the default format. The example also treats an empty string as "G", uses CultureInfo.CurrentCulture when the provider is null, and rejects unsupported formats with FormatException. The type defines its additional formats: implementing the interface does not automatically support every numeric format.
The two-parameter overload does not replace object.ToString(). In the example, a separate override of parameterless ToString() delegates to the shared implementation. string.Format passes it the format from an item such as {0:F2} and the provider. However, a provider with ICustomFormatter can take over formatting; the object's method is used when that mechanism does not handle the value.
The Distance type supports exactly "G" and "F2", plus the default null and empty string. It forwards the provider when formatting its underlying decimal value. Both calls use CultureInfo.InvariantCulture, so the expected lines are 12.5 m and 12.50 m, independently of the current culture.
Examples
#nullable enable
using System;
using System.Globalization;
var distance = new Distance(12.5m);
IFormattable value = distance;
Console.WriteLine(value.ToString(null, CultureInfo.InvariantCulture));
Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "{0:F2}", distance));
public sealed class Distance : IFormattable
{
private readonly decimal meters;
public Distance(decimal meters) => this.meters = meters;
public override string ToString() =>
ToString("G", CultureInfo.CurrentCulture);
public string ToString(string? format, IFormatProvider? formatProvider)
{
formatProvider ??= CultureInfo.CurrentCulture;
return format switch
{
null or "" or "G" => meters.ToString("G", formatProvider) + " m",
"F2" => meters.ToString("F2", formatProvider) + " m",
_ => throw new FormatException("Unsupported format: " + format)
};
}
}Result
12.5 m 12.50 m
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.