FREE BOOK

Chapter 2: Creating Versatile Types

Posted by SAMS Publishing Free Book | C# Language March 24, 2010
Tags: C#
This chapter is all about making your own objects as useful and versatile as possible. In many cases, this means implementing the standard interfaces that .NET provides or simply overriding base class methods.

Format a Type with ToString()

Scenario/Problem: You need to provide a string representation of an object for output and debugging purposes.

Solution: By default, ToString() will display the type's name. To show your own values, you must override the method with one of your own. To illustrate this, let's continue our Vertex3d class example from the previous chapter.

Assume the class initially looks like this:

struct Vertex3d
{
    private double _x;
    private double _y;
    private double _z;

    public double X
    {
        get { return _x; }
        set { _x = value; }
    } 

    public double Y
    {
        get { return _y; }
        set { _y = value; }
    } 

    public double Z
    {
        get { return _z; }
        set { _z = value; }
    } 

    public Vertex3d(double x, double y, double z)
    {
        this._x = x;
        this._y = y;
        this._z = z;
    }

}

Override ToString() for Simple Output

To get a simple string representation of the vertex, override ToString() to return a string of your choosing.

public override string ToString()
{
    return string.Format("({0}, {1}, {2})", X, Y, Z);

}

The code

Vertex3d v = new Vertex3d(1.0, 2.0, 3.0);
Trace.WriteLine(v.ToString());

produces the following output:

(1, 2, 3)

Total Pages : 12 12345

comments