How to prevent a base class's method from being run

JeffinAtl 161 Reputation points
2021-08-12T04:56:38.803+00:00

I have base class and derived class and base class has a method like following.

public class Base()
{
    public Base()
    {
        methodA();
    }
    public void methodA()
    {
        //do something
    }
}
public class Derived()
{
    public Derived()
    {
    }
}

From other part, I can instantiate class Base or class Derived.
The methodA() is called when I instantiate class Derived.
I want to let the methodA() is called only when I instantiate class Base, not class Derived.
How to do this?

Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.6K Reputation points
    2021-08-12T07:37:33.467+00:00

    If it cannot be done at compile time, then do it at run time, for example:

    public Base( )
    {
       if( this.GetType( ) == typeof( Base ) )
       {
          methodA( );
       }
    }
    
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Daniel Zhang-MSFT 9,651 Reputation points
    2021-08-12T05:42:42.923+00:00

    Hi JeffinAtl-3170,
    You can prevent derived classes from accessing members of the base class by using the private access modifier in the base class, so methods in the base class can be marked as private.
    Although this method is still inherited, it cannot be accessed in derived classes.
    And there is a problem with your code, the definition of the class does not need parentheses.
    Please refer to the following code:

    public class Base  
    {  
        public Base()  
       {  
        methodA();  
        }  
        private void methodA()  
        {  
           Console.WriteLine("hello");      
         }  
    }  
    public class Derived: Base  
    {  
         public Derived()  
         {  
         }  
    }  
    

    Best Regards,
    Daniel Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.