Inheritance C # ToString

I have a problem (this is my mistake, I just can not understand what I'm doing wrong), where "ToString" does not call the correct method ...

public class ClassA
{
   public override ToString()
   {
      return "Hello, I'm class A.";
   }
}

public class ClassB : ClassA
{
   public override ToString()
   {
       return "Hello, I'm class B.";
   }
}

ClassB myClassB = new ClassB();
List<ClassA> myClassAList = new List<ClassA>();

myClassAList.Add((ClassA) myClassB);
ClassA tempClassA = myClassAList[0];
Console.WriteLine(tempClassA.ToString());

I get "ToString" from "ClassB" and not "ClassA", what am I doing wrong?

+3
source share
4 answers

You override ToString in ClassB instead of hiding it from the original, which will cause the overridden method to take precedence. What you can do is ...

public class ClassA
{
    public override string ToString()
    {
        return "Hello, I'm class A.";
    }
}

public class ClassB : ClassA
{
    public new string ToString()
    {
        return "Hello, I'm class B.";
    }
}

...

List<ClassA> theList = new List<ClassA>
{
    (ClassA)new ClassB(),
    (ClassA)new ClassB()
};

ClassA a = theList[0];
Console.WriteLine(a.ToString());

// OR... 

Console.WriteLine(new ClassA().ToString());  // I'm Class A
Console.WriteLine(new ClassB().ToString());  // I'm Class B
Console.WriteLine(((ClassA)new ClassB()).ToString()); // I'm Class A
+4
source

- . ClassB ClassA, ClassB. .ToString() ClassB.ToString(), .

+6

ToString - , , , , .

, , , ClassA ToString.

, . , "tempClassA", ClassB, ClassB, ToString .

0

You get the right results. You add an instance of ClassB to your list; even if you consider it as ClassA. Therefore, when you call the virtual ToString method, this will result in a call to ClassB ToString; because it is the actual type of object you are working with.

0
source

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


All Articles