The new operator in C# isn't overriding base class member

Posted by Dominic Zukiewicz on Stack Overflow See other posts from Stack Overflow or by Dominic Zukiewicz
Published on 2010-06-18T12:38:13Z Indexed on 2010/06/18 12:43 UTC
Read the original article Hit count: 274

Filed under:
|
|

I am confused as to why the new operator isn't working as I expected it to.

Note: All classes below are defined in the same namespace, and in the same file.

This class allows you to prefix any content written to the console with some provided text.

public class ConsoleWriter
{
    private string prefix;

    public ConsoleWriter(string prefix)
    {
        this.prefix = prefix;
    }

    public void Write(string text)
    {
        Console.WriteLine(String.Concat(prefix,text));
    }
}

Here is a base class:

public class BaseClass
{
    protected static ConsoleWriter consoleWriter = new ConsoleWriter("");

    public static void Write(string text)
    {
        consoleWriter.Write(text);
    }
}

Here is an implemented class:

public class NewClass : BaseClass
{
    protected new static ConsoleWriter consoleWriter = new ConsoleWriter("> ");
}

Now here's the code to execute this:

class Program
{
    static void Main(string[] args)
    {
        BaseClass.Write("Hello World!");
        NewClass.Write("Hello World!");

        Console.Read();
    }
}

So I would expect the output to be

Hello World!
> Hello World!

But the output is

Hello World
Hello World

I do not understand why this is happening. Here is my thought process as to what is happening:

  1. The CLR calls the BaseClass.Write() method
  2. The CLR initialises the BaseClass.consoleWriter member.
  3. The method is called and executed with the BaseClass.consoleWriter variable

Then

  1. The CLR calls the NewClass.Write()
  2. The CLR initialises the NewClass.consoleWriter object.
  3. The CLR sees that the implementation lies in BaseClass, but the method is inherited through
  4. The CLR executes the method locally (in NewClass) using the NewClass.consoleWriter variable

I thought this is how the inheritance structure works?

Please can someone help me understand why this is not working?

© Stack Overflow or respective owner

Related posts about c#

Related posts about inheritance