3

I'm a beginner to c# programming and recently started working on a bachelors degree. What I'm trying to say is, I'm new.

I have marked the place where I have the problem. The problem is that I don't understand why I need to put override in the code at all.

There is 2 var of the type object (first and rest).

public Pair()
  {
    first = rest = null;
  }

public Pair(Object o)
  {
    first = o;
    rest = null;
  }

public Object First()
  {
    return(first);
  }
public Object Rest()
  {
    return(rest);
  }

public Pair Connect(Object o)
  {
    rest = o;
    return(this);
  }

//Here is the "override string ToString" I don't understand. Why do I need to override this?

 public override string ToString()
  {
    string output = "(";
Pair p = this;
while (p != null) {
      if (p.First() == null)
        output += "NULL";
      else
        output += p.First().ToString();
      if (p.Rest() is Pair)
    p = (Pair)(p.Rest());
      else {
    if (p.Rest() != null)
          output += " . " + rest.ToString();
    break;
  }
  output += " ";
}
    output += ")";
    return(output);
}
  • 1
    You don't have to override it, however it is useful in a lot of scenarios. Like in `Exceptions` or when you `debug`. If you do `Console.WriteLine(new Pair());` it will actually call the `ToString` method – kevintjuh93 Oct 16 '15 at 09:29
  • Every object has a ToString, image you had a class called Person and it had properties like FirstName, Lastname & etc. sometimes it's preferable to override the ToString method to return say FirstName + " " + Surname. Instead of the default "NameSpace.Person" – Jeremy Thompson Oct 16 '15 at 09:31
  • Never write code you don't understand. It is guaranteed that you'll discover by yourself why overriding ToString() can be useful. – Hans Passant Oct 16 '15 at 10:10
  • Related post - [Why / when would it be appropriate to override ToString?](https://stackoverflow.com/q/10278049/465053) – RBT Sep 06 '18 at 06:17

2 Answers2

2

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.

npinti
  • 51,780
  • 5
  • 72
  • 96
  • You should probably mention the reason you need to override it is because it is already implemented in the Object class, from which all others objects derive from. – kkyr Oct 16 '15 at 09:31
  • @kyriacos_k: That answer is already taken care of by `Amadan`. – npinti Oct 16 '15 at 09:39
  • Now that c# 6 is released. You can use `$"..."` to format a string! – Sweeper Nov 16 '15 at 06:57
0

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.

Amadan
  • 191,408
  • 23
  • 240
  • 301