4

If you are writing code in a class that inherits from a base class and you want to call a protected or public method on that base class, is it best (right or wrong or otherwise) to call base.MyProtectedMethod() or this.MyProtectedMethod() (in c#)? What would the difference be? Both seem to work.

For example:

public class MyBase()
{
    ....

    protected void DoStuff()
    {
        // some stuff
    }

}

public class MyChildClass() : MyBase
{

    public MyNewMethod()
    {
        // do some work

        this.DoStuff();
        base.DoStuff();
    }
}

Does this just to the same thing twice in MyNewMethod?

user7116
  • 63,008
  • 17
  • 141
  • 172
Stuart Helwig
  • 9,318
  • 8
  • 51
  • 67

3 Answers3

10

This does exactly the same thing in MyNewMethod.

I would only recommend using base. when it is actually required, ie: when you need to explicitly calling the base class version of a method from within an overridden method.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • 2
    Note that this is only the case because the child class does not actually implement/override the method being called. – Jeff Mercado Mar 23 '11 at 01:06
2

Do you want to explicitly call up the parent class? Then use base.

If you don't want to, use this.

This shows a great example on using base.

1

Just to illustrate Reed and Kevin's answers:

namespace ConsoleApplication1
{
    class A
    {
        public virtual void Speak()
        {
            Hello();
        }
        virtual protected void Hello()
        {
            Console.WriteLine("Hello from A");
        }
    }

    class B : A
    {
        public override void Speak()
        {
            base.Hello(); //Hello from A
            this.Hello(); //Hello from B
        }

        override protected void Hello()
        {
            Console.WriteLine("Hello from B");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {

            B b = new B();
            b.Speak();
        }
    }
}
Giovanni Galbo
  • 12,963
  • 13
  • 59
  • 78