By 27/01/2014 6 Comments

How To Format a Type with ToString() in C#

Format a type

  • Some time we need to format a type.


  • By default, ToString() will display the type’s name (class name).  To show your own values, you must override this method with one of your own.
  • The job of ToString() method is: it converts an object into string form and returns that object’s information in string representation as it can be easily displayed and becomes human readable.

Here is the code which defines a ToString() Method for a Class.

 class Program
      static void Main(string[] args) // main method
        var tt = new TutorialsTown(1.0, 2.0, 3.0); // creating an object of bellow class,calling the constructor pass 3 arguments to the constructor
        Console.WriteLine(tt.ToString()); // display our own formatted values

 class TutorialsTown
     public double A { get; set; }
     public double B { get; set; } // initialize auto properties of double type
     public double C { get; set; }

 public TutorialsTown(double a, double b, double c) // parametrized constructor, a special type of method which initialize the instance variables or fields, return no any types nor void 
     this.A = a; this.B = b; this.C = c; // auto properties initialization inside constructor 

 public override string ToString() // toString() method is being override because we want to display our own values instead of default value which is a class name
     return string.Format("({0}, {1}, {2})", A, B, C); // here return the string which is wrapped inside the Format() method, this method is associated with string class

Posted in: C#.NET

Leave your valuable Comment

Have a natural attraction for women cosmetics and replica watches uk clothes, no
more than two for men the most attractive one, is to make their own driving experience, happy and can serve as the facade of the car, another is to highlight the taste edify sentiment rolex replica watch. The replica rolex is undoubtedly the most fashionable accessories, wear a suit to attend the activities, but also get a decent match on the replica watches .