If you call base.methodName or this.methodName

If you write code in a class that inherits from a base class and you want to call a protected or public method in this base class, it is better (right or wrong or otherwise) to call base.MyProtectedMethod() or this.MyProtectedMethod() (in C #) ? What is the difference? Both seem to work.

For instance:

 public class MyBase() { .... protected void DoStuff() { // some stuff } } public class MyChildClass() : MyBase { public MyNewMethod() { // do some work this.DoStuff(); base.DoStuff(); } } 

Is it the same thing twice in MyNewMethod ?

+4
source share
3 answers

It does the same in MyNewMethod .

I would recommend using base. when it is really necessary, i.e. when you need to explicitly call the version of the base class of a method from an overridden method.

+10
source

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

If you do not want, use this .

This is a great example of using base .

+2
source

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(); } } } 
+1
source

Source: https://habr.com/ru/post/1344855/


All Articles