Defines a mechanism for a value to present itself to a user for formatting.
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.
Formats the current IFormattable
object using the specified format and culture-specific information.
format
: A string that contains one or more format specifiers.provider
: An object that supplies culture-specific formatting information. If null, the current culture is used.The value of the current instance in the specified format.
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.
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"))}");