Tuesday 21 August 2018

C#: toString method

‘toString’ method returns the string representation of the object. By default all the classes has access to this method. ‘toString’ method defined in System.Object class. Since all the classes inherit from System.Object class, the methods available in System.Object class are available to all the classes.

Why to override toString method?
It is always good practice to provide string representation of custom objects.
While logging information about any object, it gives meaningful information to the user.

Program.cs
using System;

class Student
{
    public String name;
    public int id;

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public int getId()
    {
        return id;
    }

    public void setId(int id)
    {
        this.id = id;
    }

    public Student(String name, int id)
    {
        this.name = name;
        this.id = id;
    }

    public override string ToString()
    {
        String info = "id : " + id + ", name : " + name;
        return info;
    }

}

class Program
{
    static void Main()
    {
        Student s1 = new Student("Hari Krishna", 1);

        Console.WriteLine(s1.ToString());
    }
}

Output
id : 1, name : Hari Krishna


Previous                                                 Next                                                 Home

No comments:

Post a Comment