Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Call Method in Base Class

I have 2 classes:

public class A
{
    public void WriteLine(string toWrite) { Console.WriteLine(toWrite); }
}

public class B : A
{
    public new void WriteLine(string toWrite) { Console.WriteLine(toWrite + " from B"); }
}

In my code I do the following:

B writeClass = new B();
writeClass.WriteLine("Output"); // I expect to see 'Output from B'
A otherClass = (A)writeClass;
otherClass.WriteLine("Output"); // I expect to see just 'Output'

I presumed this would work because of polymorphism.

However, it always writes 'Output from B' every time. Is there anyway to get this to work the way I want it to?

EDIT Fixing code example.

like image 948
Brandon Avatar asked Jul 08 '26 04:07

Brandon


1 Answers

When you "hide" a method from the base class using NEW you are just hiding it, thats it. It's still called when you explicitily call the base class implementation.

A doesnt contain WriteLine so you need to fix that. When I fixed it I got

Output from B
Output


namespace ConsoleApplication11
{
    class Program
    {
        static void Main(string[] args)
        {
            B writeClass = new B(); 
            writeClass.WriteLine("Output"); // I expect to see 'Output from B' 
            A otherClass = (A)writeClass; 
            otherClass.WriteLine("Output"); // I expect to see just 'Output' 
            Console.ReadKey();
        }
    }

    public class A
    {
        public void WriteLine(string toWrite) { Console.WriteLine(toWrite); }
    }
    public class B : A
    {
        public new void WriteLine(string toWrite) { Console.WriteLine(toWrite + " from B"); }
    }
}
like image 90
Dustin Davis Avatar answered Jul 10 '26 18:07

Dustin Davis