C# ToString Method

Description

The ToString method returns the default textual representation of a type instance. This method is overridden by all built-in types.

Here is an example of using the int type's ToString method:


int x = 1;
string s = x.ToString();     // s is "1"

Example

Example for a simple ToString method


using System;/*ww w .java 2s . c  o m*/
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:

Example 2

The following code overrides the ToString method to print out first name and last name for employee object.


using System;/*from  w w w  .  j  av  a 2 s  .  c  om*/

public class Employee
{
  public string firstName;
  public string lastName;

  public Employee(string firstName, string lastName)
  {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  public override string ToString()
  {
    return firstName + " " + lastName;
  }
}

class MainClass
{
  public static void Main()
  {
    Employee myEmployee = new Employee("A", "M");
    Employee myOtherEmployee = new Employee("B", "N");

    Console.WriteLine("myEmployee.ToString() = " + myEmployee.ToString());
    Console.WriteLine("myOtherEmployee.ToString() = " + myOtherEmployee.ToString());
  }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor