ToString method

The ToString method should provide the string representation of an object.

We can override ToString() method for Rectangle.


using System;
class Rectangle{
   public int Width;
   public int Height;
   
   public string ToString(){
     return "Rectangle: "+ Width+" by "+ Height;
   }
}


class Program
{
    static void Main(string[] args)
    {
        Rectangle r = new Rectangle();
        r.Width = 4;
        r.Height = 5;
        Console.WriteLine(r);

    }
}

The output:


Rectangle: 4 by 5
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.