Why do I need to override ToString?

江枫思渺然 提交于 2019-12-06 09:15:35

You override the ToString method whenever you have an object and you would like to change the way it is represented as a string.

This is usually done for formatting options, so that when you print items to console you have control over how they are displayed to who ever is viewing them.

For instance, given this class:

    class Person
    {
        public int Age { get; set; }
        public string Name { get; set; }
    }

Printing an instance of the Person class to console would yield: namespace+classname, which from a readability point of view is not ideal.

Changing the class to this:

    class Person
    {
        public int Age { get; set; }
        public string Name { get; set; }

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

Yields: Name: ... Age: ... where the ellipses denote the values provided. This is more readable than the previous scenario.

If your question is "why should overriding of ToString be useful", npinti has the answer.

If your question is "why do I use override on ToString but not on other methods", then the answer is: because ToString is defined on the ancestor classes, and the other methods you are defining aren't. The compiler will complain if you override an inherited method without tagging it with the override keyword, just as a sanity check to see if that's really what you wanted to do, or if you forgot that this method existed in ancestry.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!