Share via


Overriding OnPaint and ToString (C# Programming Guide) 

Overriding existing methods in order to add extra features.

Overriding OnPaint

C# versioning features are particularly useful when writing code that uses Windows Forms. For example, it is common is to override the OnPaint method provided by a control inherited from a Windows Form.

Overriding OnPaint enables your program to make use of the Windows Forms' existing Paint event by including the extra code that is required to draw your custom control.

protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
{
    // Perform custom drawing
    System.Drawing.Graphics gfx = e.Graphics;
    gfx.DrawString("Hello, World!",
      new System.Drawing.Font("Arial", 16),
      new System.Drawing.SolidBrush(System.Drawing.Color.Blue),
      new System.Drawing.Point(10, 10));
}

For more information, see User-Drawn Controls.

Overriding ToString

Every object in C# inherits the ToString method, which returns a string representation of that object. For example, all variables of type int have a ToString method, allowing them to return their contents as a string:

int x = 42;
string strx = x.ToString();
System.Console.WriteLine(strx);

By overriding the ToString method, you can control the default string that an object returns. This can be useful when debugging or tracing the execution of a program:

class SampleObject
{
    int number = 42;

    public override string ToString()
    {
        return "Object: SampleObject. Value: " + number;
    }
}

When an instance of this type is created, the ToString method can be called like this:

SampleObject o = new SampleObject();
System.Console.WriteLine(o.ToString());

And the following output is produced:

Object: SampleObject. Value: 42

If you need more information about the contents of an object when tracing the operation of your program, you should make use of Visual Studio's debugging tools. The debugger will display the contents of variables with DataTips, and using visualizers, you can display text, HTML, XML and datasets. For more information, see How to: Use DataTips and Visualizers.

See Also

Reference

Objects, Classes and Structs (C# Programming Guide)
new (C# Reference)
override (C# Reference)
virtual (C# Reference)

Concepts

C# Programming Guide