ToString virtual marking in base class, what happens?

Consider the following example (LinqPad). ToString in class X is marked as virtual. Why is the output here not "Hello, I am Y, Hello, I am X", but instead the type name is printed? Of course, the labeling of ToString virtual is incorrect, because it is defined in Object as virtual, I'm just trying to understand what is happening here.

void Main()
{
    Y y = new Y();
    Console.WriteLine(y);
}

// Define other methods and classes here

class X
{
  public virtual String ToString() 
  {
    return "Hi, I'm X";
  }
}

class Y : X
{
  public override String ToString() 
  {
    return "Hi, I'm Y, " + base.ToString();
  }
}
+3
source share
2 answers

This is the creation of a new virtual method in X, called ToString(), which hides Object.ToString(). Therefore, if you have:

Y y = new Y();
X x = y;
Object o = y;

Console.WriteLine(y.ToString()); // Shows "Hi, I'm Y, Hi, I'm X";
Console.WriteLine(x.ToString()); // Shows "Hi, I'm Y, Hi, I'm X";
Console.WriteLine(o.ToString()); // Calls object.ToString; shows just "Y"

The challenge is easy

Console.WriteLine(y);

equivalent to the final line, so the type name is printed.

, X.ToString Object.ToString():

public override String ToString() 
{
    return "Hi, I'm X";
}
+15

virtual String ToString() class X, "" object.ToString , .

Console.WriteLine(y);, object.ToString(). , .

:

1 'X.ToString()' . ToString() '. , . .

+8

Source: https://habr.com/ru/post/1791042/


All Articles