IFormattable Interface in C#

The IFormattable interface in C# allows you to define a custom string representation for an object. This is especially useful when you want to support various string representations for a type, possibly based on different cultures.

IFormattable Interface Definition

The IFormattable interface is defined as follows:

public interface IFormattable
{
string ToString(string format, IFormatProvider formatProvider);
}
  • format: This is a string that specifies the format. For built-in types, it could be something like "C" for currency or "D" for decimal, among others.
  • formatProvider: This provides culture-specific information for formatting. In most cases, this will be an instance of CultureInfo.

Example

Let's say you have a Temperature class, and you want to be able to format it in either Celsius or Fahrenheit. You can implement the IFormattable interface to achieve this:


public class Temperature : IFormattable
{
public double Celsius { get; }

public Temperature(double celsius)
{
	Celsius = celsius;
}

public string ToString(string format, IFormatProvider formatProvider)
{
	if (string.IsNullOrEmpty(format))
		format = "C";

	switch (format.ToUpper())
	{
		case "C":
			return $"{Celsius} °C";
		case "F":
			return $"{Celsius * 9.0 / 5.0 + 32} °F";
		default:
			throw new FormatException($"The {format} format string is not supported.");
	}
}
}

With this implementation, you can format a Temperature object as follows:


var temp = new Temperature(25.0);
Console.WriteLine(temp.ToString("C", null)); // Outputs: 25 °C
Console.WriteLine(temp.ToString("F", null)); // Outputs: 77 °F

Benefits of IFormattable:

  1. Custom Formatting: As shown in the example, it gives classes the flexibility to have custom string representations.
  2. Culture-specific Formatting: With the IFormatProvider, you can provide culture-specific representations. For instance, numbers, dates, and currencies can be formatted differently based on different cultures.
  3. Consistency with .NET Framework: Many built-in .NET types, like DateTime and numeric types, implement IFormattable. By using it in custom types, you make them consistent with the rest of the framework.
  4. Enhanced Integration: Types that implement IFormattable can be better integrated with methods and utilities that expect this interface, like string.Format().

In conclusion, the IFormattable interface is a valuable tool in C# for creating types that have customizable and culture-aware string representations.