O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required