I read a book and saw the following code example:

public class Man { public string Name; public override string ToString() => Name; } ... Man p = new Man { Name = "Piter" }; Console.WriteLine (p); //Piter 

It is not clear what does ToString do with it at all, and why do we print the name by simply invoking an instance without specifying a field?

  • "... invoking the instance"? The console displays a string representation of the object, which is obtained by calling the virtual method ToString . - Igor
  • that is, I can reassign the ToString inside the method and specify what it will do when called. And with each call to p (not p.name and not p.ToSrting() ), I will output exactly what was defined inside public override string ToString() => Name; ? - Nikolay

2 answers 2

According to the documentation for the Console.WriteLine method:

If the value passed in is null , only the newline is printed. Otherwise, the result of calling the ToString function is ToString

ToString redefined to display the Name field, so it is printed when you call WriteLine

  • aa, I see .. It is a pity that not a word about this in the textbook .. It was necessary to immediately think about the documentation, thank you) - Nikolay
  • @Nikolay tutorial is probably not very good. Check out the list of references . - αλεχολυτ
  • @alexolut C # 6.0. Directory. A complete description of the Albahari language I read) well, in any case, I cannot do with a single book) - Nikolay
  • @Nikolay, when you do not understand what is happening, it is useful to look into the source code of the method being called. - iksuy

Delete the line:

 public override string ToString() => Name; 

Then, when calling:

 Console.WriteLine (p); 

We will see something like:

 >>Yournamespace.Man 

Which is not very informative, especially if there are several such objects. This happens because the inherited function ToString() , displays the full class name. If you need to have ANYWHERE, where the class will be displayed on the line, there is a different behavior, you need to override this function. What was done in the above line.

  • it will leave the type name as a string, as I understand it. Then what is the meaning of the GetType function? - Nikolay
  • it is wiser to use it, since it fulfills its purpose. I understand. And at redefinition ToString will not cause an error. But without a definition can it be omitted? Question for a general understanding - Nikolay
  • one
    1. GetType returns the class type and not the string value of its name, although the name can be obtained in this way. - Mirdin
  • 2. Naturally, you can not override it, if for the behavior of the class it does not matter what it gives out. - Mirdin