Sunday, October 27, 2024

How can you call a method of base class in derived class in C#?

In C#, you cannot directly call a private method (or any member) from a base class in a derived class. Private members are not accessible outside the class in which they are defined, even in derived classes. However, if you want to call a method that's marked as protected or internal (or any other access modifier that allows visibility to derived classes), you can call it from the derived class.

Here's an example:
class BaseClass
{
    protected void SomeMethod()
    {
        Console.WriteLine("Some method in base class");
    }
}

class DerivedClass : BaseClass
{
    public void CallBaseMethod()
    {
        // You can call the protected method from the derived class
        SomeMethod();
    }
}
In this example, SomeMethod() is marked as protected in the BaseClass. The DerivedClass inherits from BaseClass, and in DerivedClass, you can call the protected method SomeMethod().

More appropriately, in C#, you can call a method from a base class in a derived class using the base keyword. This is particularly useful when you want to invoke a method that has been overridden in the derived class, or to ensure that the base class implementation is executed. Here’s a simple example to illustrate how to do this:

// Base class
public class BaseClass
{
    public void Display()
    {
        Console.WriteLine("Base class method called.");
    }
}

// Derived class
public class DerivedClass : BaseClass
{
    public void Display()
    {
        Console.WriteLine("DerivedClass method.");
}
public void CallBaseMethod() { // Calling the base class method base.Display(); } } // Example usage class Program { static void Main() { DerivedClass derived = new DerivedClass(); derived.CallBaseMethod(); // Output: Base class method called. } }
This mechanism allows for clear and controlled access to the methods of the base class from the derived class.


No comments:

Post a Comment

Hot Topics