.NET Home API Reference System Namespace

IFormattable Interface

System interface IFormattable

Defines a mechanism for a value to present itself to a user for formatting.

Summary

The IFormattable interface is implemented by types that need to provide custom formatting of their value. It is particularly useful for internationalization, allowing objects to be formatted according to specific culture-sensitive conventions. Objects that implement IFormattable can be formatted using standard formatting strings or custom format specifiers.

Members

string ToString( string format, IFormatProvider provider )

Description

Formats the current IFormattable object using the specified format and culture-specific information.

Parameters

Return Value

The value of the current instance in the specified format.

Remarks

The format parameter is used to specify how the object should be formatted. Common format specifiers include "C" for currency, "D" for decimal, "E" for scientific notation, "F" for fixed-point, "G" for general, "N" for number, "P" for percentage, "X" for hexadecimal, and "e", "f", "g", "n", "p", "x" for custom format specifiers.

The provider parameter allows you to control the culture-specific aspects of the formatting. For example, you can use CultureInfo.CurrentCulture or a specific CultureInfo object.

Example


using System;
using System.Globalization;

public class CustomDateTime : IFormattable
{
    public DateTime Value { get; set; }

    public CustomDateTime(DateTime dateTime)
    {
        Value = dateTime;
    }

    public string ToString(string format, IFormatProvider provider)
    {
        if (string.IsNullOrEmpty(format))
        {
            format = "G"; // Default to general format
        }

        // Use the DateTime.ToString overload that accepts format and provider
        return Value.ToString(format, provider);
    }

    public override string ToString()
    {
        // Fallback to default if no format/provider specified
        return ToString(null, null);
    }
}

// --- Usage Example ---
DateTime now = DateTime.Now;
CustomDateTime customDate = new CustomDateTime(now);

// Using default culture and format
Console.WriteLine($"Default: {customDate.ToString()}");

// Using French culture and a custom format
CultureInfo frenchCulture = new CultureInfo("fr-FR");
Console.WriteLine($"French (yyyy-MM-dd HH:mm): {customDate.ToString("yyyy-MM-dd HH:mm", frenchCulture)}");

// Using US culture and currency format for a decimal (example of how IFormattable is used)
decimal price = 123.45m;
Console.WriteLine($"USD: {price.ToString("C", CultureInfo.GetCultureInfo("en-US"))}");
                

See Also

Note: This documentation provides a reference for the .NET Framework API. Functionality and availability may vary across different versions of the .NET ecosystem.