Tuesday, March 23, 2010

Overriding the ToString Method

The ToString method is one of the most important methods in the .NET library as it always works in the background with the methods Console.WriteLine. It is used to convert an expression to a string. As we know , we can use it explicitly like this:
Console.WriteLine(myVariable.ToString());
but if we omit the ToString method, which is always the case since it is embedded, we still get the same result.
This method is an override method defined in the class Sustem.AppDomain as follows:
public override string ToString();
In some cases we might need to override it to change its behavior, such as when we would like to display an object as if it were a regular variable. Instead of displaying a Point object like this (as in the example above):
Console.WriteLine(“Point #1: {0}, {1})”, p1.x,p1.y);
We can display it like this:
Console.WriteLine(“Point #1: {0}”,p1);
To do that, we must override the method ToString to be able to display objects of the type Point. Here is an example of the code to do this:
//Overriding the ToSting method:
public override string ToString()
{
    return (String.Fromat(“({0},{1})”,x,y));
}
In this code segment, the String.Format method replaces the format items, {0} and {1}, with the text equivalent to the value of the specified objects, x and y. Thus, the output of this method would be the values of the point (x,y). We can add this method to the preceding example and display the Point objects directly as single variables.

No comments:

Post a Comment