Search code examples
c#inheritancethisradix

When I inherit a method in C# and call the inherited method. Do I need to use base or this


When we inherit a method in C# how it the best way to call it. With base or this. Here are some example:

   class User
    {
        public void LogData()
        {
            Console.WriteLine($"Log data from user");
        }
    }

    class Admin : User
    {
        public void DeleteData()
        {
            // How is it right way to call that method?
            // base.LogData();
            // or
            // this.LogData();
            Console.WriteLine("Deleting");
        }
    }

Solution

  • You would only really use the base prefix to bypass the locally defined method of the same name within the class who's context execution currently resides.

    this.LogData() will behave the same as LogData() in the example above.

    base.LogData() will call the LogData defined on the base class, but it is important to note that during that execution context, LogData will see the 'this' class as a 'User' type class, and not an 'Admin' class. This is because of the inheritance model. Every 'Admin' may be a 'User', but not all 'Users' are 'Admins'.

    If your execution manages to get into the base class, the LogData method will only have access to members on the User class - because at that point in time, the Admin user has been implicitly cast back into a 'User' class for the duration of the method execution.

    As mentioned above - there is the 'new' keyword - you can use to disable the warning associated with 'hiding' methods. It should be noted, that I think the 'new' keyword only functions as a means to disable the warning, it does not actually facilitate the overriding of a method.

    https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/knowing-when-to-use-override-and-new-keywords

    If you wish to override and create methods of the same name within derived classes, you should use virtual and override where appropriate. More information about them can be found at the link above.

    bc.Method1();  
    bc.Method2();  
    dc.Method1();  
    dc.Method2();  
    bcdc.Method1();  
    bcdc.Method2();
    public override void Method1()  
    {  
        Console.WriteLine("Derived - Method1");  
    }  
    
    
    public virtual void Method1()  
    {  
        Console.WriteLine("Base - Method1");  
    }  
    
    
    // Output:  
    // Base - Method1  
    // Base - Method2  
    // Derived - Method1  
    // Derived - Method2  
    // Derived - Method1  
    // Base - Method2