CopyPastehas never been so tasty!

Override ToString() method in C#

by anonymous

  • 0
  • 0
  • 0
74 views

Orignal source:http://codingvilla.com/override-tostring-method-csharp-single-article-603.aspx

 Method overriding:

 

Method overriding means two methods which have same names but different implantation. This method has its signature in parent class and implementation in subclass.

 

Override ToString Method:

 

To override the ToString method, first we will declare a ToString method as mentioned below.

 

public override string ToString(){}

 

To override ToString method we use override modifier.  This method modifies this method. This method has same signature but it has different implementation. This method will return a string.

 

To demonstrate make a console application and write the following code.

 

Code:

 

classCar

    {

 

publicstring manufacturer;

publicstring model;

 

 

public Car(string manufacturer, string model)

  {

this.manufacturer = manufacturer;

this.model = model;

  }

 

// override the ToString() method

publicoverridestringToString()

  {

return manufacturer + " " + model;

  }

 

 

staticvoid Main(string[] args)

        {

 

 

CarmyCar = newCar("Lamborghini", "Murcielago");

CarmyOtherCar = newCar("Porsche", "911 carrera");

Console.WriteLine(myCar.ToString());

Console.WriteLine(myOtherCar.ToString());

Console.ReadLine();

 

        }

    }

 

 

Add A Comment: