Friday, April 23, 2010

Overriding – ToString () – A Simplest approach to understand it

In C# Overriding can be achieved by use of the "override" keyword. To override a method means to replace it with a new way of handling data; I mean replacing the default behavior or extending it.

Here's an example of what I mean:
public class SimpleCar
 {
      int vwidth, vheight; //Private Data Member
      public int cWidth {  set { vwidth = value; } get { return vwidth; } }
      public int cHeight { set { vheight = value; } get { return vheight; } }
      public int cArea {  get { return (vwidth * vheight); }}
     //Not Overrided built-in ToString() method
 }
Moving forward with overriding,We will take help of “ToString()” method.As we know ToString is a built-in method that returns the name of the type of the object(in case of custom type).

Have a look at the Main() method which is used to call SimpleCar-
   namespace ConsoleApplication1 {
      class Program {
            static void Main(string[] args) {
                    SimpleCar mySimpleCar1 = new SimpleCar();
                    mySimpleCar1.cWidth = 13;
                    mySimpleCar1.cHeight = 15;

                   Console.WriteLine("The area occupied by {0}, width={1} and height={2} is: 
                   {3}.", mySimpleCar1, mySimpleCar1.cWidth, mySimpleCar1.cHeight,  mySimpleCar1.cArea);

                   Console.ReadLine(); }
       }
   }

Exact output will be:
The area occupied by ConsoleApplication1.SimpleCar, width=13 and height=15 is: 195.

*Here ‘ConsoleApplication1.SimpleCar’ name comes through the help of ToString() method, As I explained earlier. Now we will simply override built-in ToString() method in our code and then we’ll see what we get.

public class SimpleCar {
       int vwidth, vheight; //Private Data Member
       public int cWidth { set { vwidth = value; } get { return vwidth; } }
       public int cHeight { set { vheight = value; } get { return vheight; } }
       public int cArea { get { return (vwidth * vheight); } }

       //Overrided built-in ToString() method
       //Here I have provided an alias for the class(-type-)
       public override string ToString()  { return "Overrided SimpleCar"; }
}

The only change between this method and any other method is the use of the ‘override’ keyword. It is as simple as earlier. Now when the same Main() method is executed, the output will be:

The area occupied by Overrided SimpleCar, width=13 and height=15 is: 195.

I hope you get the reason, How ‘Overrided SimpleCar’ came into the picture.By overriding – I mean we have replaced the default behavior of built-in ToString () method.
-As of now we get bit understanding of overriding; now we need to delve into overloading and overriding together.
-
*Hasbro Power Tour Electric Guitar (Black)

No comments:

Post a Comment