Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

IFormatProvider — supplying formatting information

System.IFormatProvider supplies information used during formatting and parsing. Its single method, GetFormat, returns an object of the requested type or null when the provider does not support that type.

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

Syntax

public interface IFormatProvider
{
    object? GetFormat(Type? formatType);
}

System.IFormatProvider supplies information for formatting values as text and parsing text into values. It is available in .NET 10 and does not require preview language features. Implementations include CultureInfo, NumberFormatInfo, and DateTimeFormatInfo.

Its only method, IFormatProvider.GetFormat, has the signature object? GetFormat(Type? formatType). Formatting or parsing code passes the type of object it needs, such as typeof(NumberFormatInfo). The provider returns an object of that type, or null when it cannot supply one. The result is not formatted text.

A provider and a format string have different jobs: "F2" specifies the numeric format, while the provider supplies rules such as the decimal separator. Pass a provider explicitly to an appropriate ToString, Parse, or TryParse overload instead of relying on the current culture. In the example, CultureInfo.InvariantCulture makes the result predictably 1234.50.

Examples

using System;
using System.Globalization;

IFormatProvider provider = CultureInfo.InvariantCulture;
object? format = provider.GetFormat(typeof(NumberFormatInfo));

Console.WriteLine(format is NumberFormatInfo);
Console.WriteLine(1234.5m.ToString("F2", provider));

Result

True
1234.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