guo guo - 2 months ago 18
C# Question

C#: Access modifier make method invoke differently

First of all, here is the code and the result is what expect:

code 1:

using System;

namespace ConsoleApplication11
{
class DerivedClass : Base
{
public new void Run()
{
Console.WriteLine("Derived class");
}
}

class Base
{
public void Run()
{
Console.WriteLine("Base class");
}

static void Main(string[] args)
{
DerivedClass dc = new DerivedClass();
Base bc = new Base();

dc.Run();
bc.Run();
}
}
}


result 1:


Derived class

Base class





However, if I change both of two classes'
Run()
access modifiers from
public
to
protected
, thing became out of expect:

code 2:

using System;

namespace ConsoleApplication11
{
class DerivedClass : Base
{
protected new void Run()
{
Console.WriteLine("Derived class");
}
}

class Base
{
protected void Run()
{
Console.WriteLine("Base class");
}

static void Main(string[] args)
{
DerivedClass dc = new DerivedClass();
Base bc = new Base();

dc.Run();
bc.Run();
}
}
}


result 2:


Base class

Base class


My question is, under the circumstances that
protected
also allow the derived class to access the base class as
public
, Why does the result become different?

Answer

DerivedClass.Run is protected, so Base doesn't even see it. It invokes the Run method inherited from Base.

Comments