Override .ToString method c#

后端 未结 7 2064
北海茫月
北海茫月 2020-11-27 07:52

Okay, so I wrote this program out of the exercise of a C# programming book (I\'m trying to learn here) and it asks for \"Override the ToString() method to return all

7条回答
  •  北海茫月
    2020-11-27 08:17

    The reason people override the ToString() method is to have a default string representation of your object, usually for display to the user or in a log or console, like this:

    Console.WriteLine(yourClassObject);
    

    If you do not override the ToString(), then its default implementation is to return the fully qualified name of your object, like this:

    YourNamespace.YourClassName
    

    By changing the inherited implementation (from System.Object), then you can make a nicer (read: prettier) representation, like this:

    public override string ToString()
    {
        return String.Format("This instance of my object has the following: Name = {0}, Number = {1}, Date = {2}, Salary = ${3}", _name, _number, _date, _salary);
    }
    

提交回复
热议问题