Book Store  
  Contact Us  
  Links  
  Site Map  
C# Tutorials - overriding functionality

Overriding Functionality

 

Objects and the ToString() Method

It is often necessary to output a representation of a variable which is quite easy with basic data types such as int and Boolean, but it is more difficult for complex data types of your own design.

Console.WriteLine(......);

If we consider how Console.WriteLine() works, you will see that the methods has a large number of overloads each able to take different data types and output as appropriately.

Console.WriteLine(12);
Console.WriteLine(false);
Console.WriteLine(“Test Value”);

The most important overload accepts the Object as its data type :

Object myObject = new Product();

Console.WriteLine(myObject);

When this code is run, the overload used will be the one that has an object as an argument.

However, the output will not be very useful. To overcome this, we can override the ToString method.

The ToString() method

Console.WriteLine and many other classes and methods make use of the built in ToString() method which is inherited into every class you create. The ToString() method is defined in the System.Object class and every class inherits from System.Object at the root level.

The default behavior of the Console.WriteLine method when passed a data type of object is to just output the data type name, not any of its properties. It would not be possible for the programmers to know what the properties would be.

That is why the output from Console.WriteLine which an object is not very useful.

Overriding the ToString() method

We can change the behavior of ToString() for the Console.WriteLine method to make it more useful.

public class Product
{

   public override string ToString()
   {
     return String.Format("{0} {1}", this.ProductID, this.ProductName);
   }

}

Note that in the Visual Studio code editor, you can type the keyword override followed by a space to see what methods are suitable to be overridden.

The override keyword informs the compiler that the method being defined replaces one which is inherited, so your code gets called in place of the inherited one.

public override string ToString()
{
    return base.ToString();
}
The keyword base can be used to call the base class methods but in out example it is not relevant.

Using the overridden ToString() method

Having overridden the ToString() method for the Product class we can use it as follows :

Product p = new Product(1, "cheese", 1.39f);

Console.WriteLine(p);
Will display :
1	cheese