简体   繁体   中英

Working of overrided ToString() in C#

i just went through following code from official msdn docs . This looks pretty simple code but 1 thing i am unable to understand that when we create object for Person and in tostring overrided method we are giving some values , now without calling this function Just an object is passed to WriteLine and it automatically prints the details of the person how is it happening , Someone Please explain it ..

using System;
class Person
{
    private string myName ="N/A";

    // Declare a Name property of type string:
    public string Name
    {
        get 
        {
           return myName; 
        }
        set 
        {
           myName = value; 
        }
    }
    public override string ToString()
    {
        return "Name = " + Name ;
    }

    public static void Main()
    {
        Person person = new Person();
        Console.WriteLine("Person details - {0}", person);
        person.Name = "Joe";
        Console.WriteLine("Person details - {0}", person);


    }
}

Output

Person details - Name = N/A 
Person details - Name = Joe 

When you pass an object, any object, to Console.WriteLine .ToString() is called. Most controls work this way as well when passed an object.

Basically, the UI doesn't know how to display a class, so .NET provides the .ToString method so it can display something . If you don't override it, notice the default gives you the fully qualified name and some other junk. The override lets you make the function useful.

The WriteLine method internally calls ToString on any object passed to it.

In your example, the first line prints the default "n/a" since you have not yet assigned a name to your object. The second line runs after setting the name to "Joe", which internally overwrites the default "n/a". Therefore, calling ToString again on the same object returns the new value for name.

From MSDN : Console.WriteLine Method (Object)

Writes the text representation of the specified object, followed by the current line terminator, to the standard output stream.

now without calling this function Just an object is passed to WriteLine and it automatically prints the details of the person how is it happening

See: Console.WriteLine

If value is Nothing, only the line terminator is written. Otherwise, the ToString method of value is called to produce its string representation, and the resulting string is written to the standard output stream.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM