Control text formatting in .NET using the IFormattable interface

Every application seems to present unique challenges for displaying text. These hurdles are easily cleared by utilizing format classes. The .NET Framework includes basic format objects for standard types, and it is easy to develop custom classes to fit your needs.

Displaying text and variable contents are a standard aspect of most development projects. In addition, it is more than likely that the output should be formatted in a particular fashion.

The .NET Framework provides various ways of achieving the desired output, including the String.Format method and format specifiers. Another way to tackle the problem involves the IFormattable interface. I'll examine how you may use this interface to control text formatting.

What is IFormattable?

The standard ToString method available with all objects allows you to easily display the contents of a variable, but it provides no control over how the data appears. The IFormattable interface provides the functionality to format the value of an object into a string representation. Classes that require more control over the formatting of strings than the standard ToString method provides should implement IFormattable.

As a quick overview, an interface is a group of methods and properties that can be implemented by several classes, regardless of where the classes are in the class hierarchy. The methods and properties of an interface are implemented in a class. When methods are implemented, the return data type and the argument data types must exactly match those of the method described in the interface. The method name, however, doesn't need to be the same as that described in the interface. An example using the IFormattable interface will make it clearer.

Format providers

Format providers supply information such as the character to use as the decimal point when formatting numeric strings, or the separation character to use when formatting a DateTime object. Format providers define the characters used for formatting by the format specifiers, but do not define the specifiers themselves.

Let's take a look at standard format providers utilized in the .NET Framework. When formatting numeric types and the DateTime structure, if no IFormatProvider implementation is provided, the two standard format provider classes (DateTimeFormatInfo and NumberFormatInfor) are used automatically to provide formatting for the related types. A simple example shows how you may be using these classes without realizing it. The following C# code displays the number as both currency and a whole number.

inttst = 550000;
System.Console.WriteLine("{0:C}", tst);
System.Console.WriteLine("{0:D}", tst);

Here's the VB.NET equivalent:

Dim tst As Integer = 550000
System.Console.WriteLine("{0:#0;(#0)}", tst)
System.Console.WriteLine("{0:#0}%", tst)

This is great when working with standard numbers, dates, and so forth, but problems may arise when working with your own custom data types/classes. This is when you utilize a custom format provider by overriding your class' ToString method.

Custom formatting

A format provider can be passed to the overload of ToString required by the IFormattable interface, or be predetermined by the method you are using to format text if no format provider is passed. Generally, classes that implement IFormattable also provide overloads of ToString that accept only a format specifier or only a format provider. The default ToString method, which accepts no parameters, is inherited from the Object class. The IFormattable interface includes only the one ToString method.

Implementing IFormattable.ToString is pretty easy, but you should overload ToString to provide a single parameter for each type. These can simply call the implementation method, which uses the format specifier and optional information from the IFormatProvider argument to format the type as a string.

Listing A contains a C# example class that utilizes this approach. It contains a property for working the value passed to it, and it implements the IFormattable interface. Various flavors of the ToString method are included to handle various formats. Listing B features the VB.NET equivalent of Listing A.

With this class in place, we can utilize it in another application to demonstrate how it may be used. Listing C is an ASP.NET example that uses it to display values via the class' ToString method. The results are displayed accordingly.

It is a simple example that accepts user input, and displays it in a Label control. Now, the text is formatted according to our CustomFormat class. The equivalent ASP.NET using VB.NET is in Listing D.

While this example is relatively simple, it does showcase the flexibility afforded by developing your own format classes. Instances always arise, especially with Web interfaces, when data must be formatted in a certain manner. Developing a custom class allows you to use the required format as well as reuse it throughout the application and tweak it in one central location.

TechRepublic's free .NET newsletter, delivered each Wednesday, contains useful tips and coding examples on topics such as Web services, ASP.NET, ADO.NET, and Visual Studio .NET. Automatically sign up today!

About Tony Patton

Tony Patton has worn many hats over his 15+ years in the IT industry while witnessing many technologies come and go. He currently focuses on .NET and Web Development while trying to grasp the many facets of supporting such technologies in a productio...

Editor's Picks

Free Newsletters, In your Inbox