Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# hiding confusion

Tags:

c#

This is confusing to me please expalin me the behaviour of this?

A declaration of a new member hides an inherited member only within the scope of the new member. Copy

**class Base
{
   public static void F() {}
}
class Derived: Base
{
   new private static void F() {}   // Hides Base.F in Derived only
}
class MoreDerived: Derived
{
   static void G() { F(); }         // Invokes Base.F
}**

In the example above, the declaration of F in Derived hides the F that was inherited from Base, but since the new F in Derived has private access, its scope does not extend to MoreDerived. Thus, the call F() in MoreDerived.G is valid and will invoke Base.F.

I am not understanding that how static void G() { F(); } can access the base class f method when it can access all methods of it's immediate super class and super class hides the f method of base class

like image 858
NoviceToDotNet Avatar asked Oct 29 '10 05:10

NoviceToDotNet


2 Answers

MoreDerived cannot access all methods of its super class; in particular, it cannot access private methods. In C#, anything marked private in a class is invisible to anything outside of that class. In other words, adding or removing a private method will not change how anything outside of that class compiles. Since the new private static void F is invisible to the outside world, MoreDerived is unaffected by it.

If the modifier was protected instead, MoreDerived would see it.

In the example you gave, the new keyword only changes the meaning of names in the namespace. It does not change what methods are available. A method of Derived can still call Base.F() like so:

class Derived: Base 
{ 
   new private static void F()
   {
       F();      // calls Derived.F()
       Base.F(); // calls Base.F()
   }
} 

class MoreDerived: Derived 
{ 
   static void G() 
   {
       F();         // Invokes Base.F
       Derived.F(); // Invokes Base.F because Derived.F is private
       Base.F();    // Invokes Base.F
   }
}

It's analogous to this example:

class Foo
{
    int bar; // in most methods, this variable can be accessed as just "bar"

    Foo(int bar) // this parameter will hide the instance member bar
    {
        this.bar = bar; // instance method can still be accessed, though
    }
}
like image 152
Gabe Avatar answered Oct 27 '22 00:10

Gabe


'new' keyword will hide the base member if it is allowded to be access outside the class.

But due to the inheritance chain MoreDerived : Derived : Base , you will see the public members of immeditae base or the higher base classes in the chain.

Method hiding is not equal to the private modifier on a method.

like image 32
TalentTuner Avatar answered Oct 27 '22 01:10

TalentTuner