DEV Community

Cover image for C# IFormattable Interface
Karen Payne
Karen Payne

Posted on

C# IFormattable Interface

Introduction

IFormattable Interface provides functionality to format the value of an object into a string representation. A simple example using a record demonstrates how to display different properties, along with formatting and calculations.

record used

  • "A" or "Age" => $"{BirthDay.GetAge()}" does a calculation
  • "B" => $"{BirthDay:O}" does special date formatting

Source code


Usage

usage for above


Output

results

Applies to

Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10, 11
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

Summary

To dive deeper, read Microsoft documentation

Note that the content is intentionally short to make it easier to learn.

Top comments (1)

Collapse
 
alexshev profile image
Alex Shev •

The example makes a good case for keeping display formats explicit. One useful guard is to have the default format throw FormatException for unsupported specifiers rather than silently falling back, then add unit tests for each named format. That prevents a typo in a report or export from producing plausible-looking but unintended output.