C# ToString Method

In this chapter you will learn:

  1. What is C# ToString Method
  2. Example for a simple ToString method
  3. Example for overriding the 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;/*  w  w  w  . ja v a2  s.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   ww  w . j a va  2s.  c  o  m

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.

Next chapter...

What you will learn in the next chapter:

  1. What are C# Object Initializers
  2. Example for C# Object Initializers
  3. Object Initializers Versus Optional Parameters
Home »
  C# Tutorial »
    C# Types »
      C# Object
C# Object
C# new operator
C# this Reference
C# Null
C# Nullable Types
C# ToString Method
C# Object Initializers
C# GetHashCode
C# Object Casting and Reference Conversions