Tuesday, November 23, 2010

String Representation of a Class Via Overloading ToString()

All objects and structures in C# inherit implicitely of the class Object. This class provides basic functions like Equals() (checks for equality) and ToString() (displays the class as string).
That means, by default all classes and structures implement these functinos too.
Most will probably know the notation Console.WriteLine(x.ToString());, it prints the value of the integer as a string. Many classes created by programmers also inherit from Object, therefore they also implement ToString(). But, this will probably not lead to the desired result. When called, the compiler simply prints the type name of the class as string, where should it know how to display the value of an instance as a string.
For that reason it might be clever to override the function ToString() in own classes. For overriding, in the child class a function with the same signature as in the father class has to be created. If now the function is called with an instance of the child class, the call is not forwarded to the base class anymore, but directly done in the child class.
The following console application implements a little class Employee, in which the function ToString() is overridden.
In the modified version, name and salary of the employee are printed out:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

class Program
{
    static void Main(string[] args)
    {
        Employee TestEmployee = new Employee("Hans Meier", 1000);
        Console.WriteLine(TestEmployee.ToString());
    }
}

class Employee
{
    public string Name;
    public int Salary;

    public Employee(string name, int salary)
    {
        Name = name;
        Salary = salary;
    }

    public override string ToString()
    {
        return "Name: " + Name + ", Salary: " + Salary + ".";
    }
}

No comments:

Post a Comment