The ToString Method - CSharp Custom Type

CSharp examples for Custom Type:Method

Introduction

The ToString method returns the textual representation of a type instance.

This method is overridden by all built-in types.

If you don't override ToString, the method returns the type name.

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

Demo Code

using System;//from w  w w .j  a va 2s.c  o m
class Test
{
   static void Main(){
      int x = 1;
      string s = x.ToString();     // s is "1"
      Console.WriteLine (s);
   }
}

Result

You can override the ToString method on custom types as follows:

Animal p = new Animal { Name = "AAA" };
Console.WriteLine (p);   
public class Animal
{
  public string Name;
  public override string ToString() => Name;
}

Related Tutorials