If it cannot be done at compile time, then do it at run time, for example:
public Base( )
{
if( this.GetType( ) == typeof( Base ) )
{
methodA( );
}
}
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
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?
If it cannot be done at compile time, then do it at run time, for example:
public Base( )
{
if( this.GetType( ) == typeof( Base ) )
{
methodA( );
}
}
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.