Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I invoke base for overriden method

Is it possible to invoke method A.F() from instance of B class except of using refactoring. Thanks..


  class Program
  {
    public class A
    {
      public virtual void F()
      {
        Console.WriteLine( "A" );
      }
    }
    public class B : A
    {
      public override void F()
      {
        Console.WriteLine( "B" );
      }
    }

    static void Main( string[] args )
    {
      B b = new B();  

      //Here I need Invoke Method A.F() , but not overrode..      

      Console.ReadKey();
    }
  }
like image 692
Yuriy Avatar asked Nov 21 '25 17:11

Yuriy


2 Answers

You may use the new keyword to have another definition of the same (named) method. Depending on the type of reference, you call A's of B's implementation.

public class A
{
  public void F()
  {
    Console.WriteLine( "A" );
  }
}
public class B : A
{
  public new void F()
  {
    Console.WriteLine( "B" );
  }
}

static void Main( string[] args )
{
  B b = new B();  

  // write "B"
  b.F();

  // write "A"
  A a = b;
  a.F();
}

If you feel that new is not the right solution, you should consider to write two methods with a distinguished name.


Generally, you can't call the base implementation from outside the class if the method is properly overridden. This is an OO concept. You must have another method. There are four ways (I can think of) to specify this distinguished method:

  • write a method with another name.
  • write a method with same name but another signature (arguments). It's called overloading.
  • write a new definition of the method with the same name (use the new keyword) It's called hiding.
  • Put it onto interfaces and implement at least one explicitly. (similar to new, but based on interface)
like image 127
Stefan Steinegger Avatar answered Nov 23 '25 06:11

Stefan Steinegger


You need base.F();

like image 43
gkrogers Avatar answered Nov 23 '25 06:11

gkrogers