3.2. Allowing a Type to Represent Itself as a String

Problem

Your class or structure needs to control how its information is displayed when its ToString method is called. For example, when creating a new data type, such as a Line class, you might want to allow objects of this type to be able to display themselves in a textual format. In the case of a Line object, it would display itself as "(x1, y1)(x2, y2)“.

Solution

Override and/or implement the IFormattable.ToString method to display numeric information, such as for a Line structure:

using System; using System.Text; using System.Text.RegularExpressions; public struct Line : IFormattable { public Line(int startX, int startY, int endX, int endY) { x1 = startX; x2 = endX; y1 = startY; y2 = endY; } public int x1; public int y1; public int x2; public int y2; public double GetDirectionInRadians( ) { int xSide = x2 - x1; int ySide = y2 - y1; if (xSide == 0) // Prevent divide-by-zero return (0); else return (Math.Atan (ySide / xSide)); } public double GetMagnitude( ) { int xSide = x2 - x1; int ySide = y2 - y1; return (Math.Sqrt( Math.Sqrt((xSide * xSide) + (ySide * ySide)) )); } // This overrides the Object.ToString method // This override is not required for this recipe // and is included for completeness public override string ToString( ) { return (String.Format("({0},{1}) ({2},{3})", x1, y1, x2, y2)); } public string ToString(string format) { return (this.ToString(format, null)); } public string ToString(IFormatProvider formatProvider) ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.