C#: Overriding a built-in method ToString

This entry is part 59 of 71 in the series C#

ToString is a common formatting method in the .NET Framework.

It converts an object to its string representation so that it is suitable for display.

Types commonly override the ToString method to return a string that represents the object instance.

For example, the Employee object contain a Name which is a string and an Age which is an Integer.  We can format them together so that they can be displayed easily in the console.

using System;

namespace StringDisplay
{
    class Employee
    {
        public string Name { get; set; }

        public int Age { get; set; }

        public override string ToString()
        {
            return string.Format("{0}:{1}",Name, Age);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            string str;

            Employee e1 = new Employee();
            e1.Name = "Megan Fox";
            e1.Age = 25;

            str = e1.ToString();
            Console.WriteLine(str);
            Console.ReadLine();
        }
    }
}

The output from running the above code will be Megan Fox:25.

megan

 

 

Series Navigation<< C#: Abstract class
C#: Default ToString method >>

Leave a comment

Leave a Reply