Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between this and base

Tags:

I am interested to know the difference between this and base object in C#. What is the best practice when using them?

like image 615
Abhishek Avatar asked Sep 17 '10 06:09

Abhishek


2 Answers

this represents the current class instance while base the parent. Example of usage:

public class Parent {     public virtual void Foo()     {     } }  public class Child : Parent {     // call constructor in the current type     public Child() : this("abc")     {     }      public Child(string id)     {     }      public override void Foo()     {          // call parent method         base.Foo();     } } 
like image 152
Darin Dimitrov Avatar answered Sep 22 '22 18:09

Darin Dimitrov


The two keywords are very different.

  • this refers to the current instance (not the “current class”). It can only be used in non-static methods (because in a static method there is no current instance). Calling a method on this will call the method in the same way as it would if you called it on a variable containing the same instance.

  • base is a keyword that allows inherited method call, i.e. it calls the specified method from the base type. It too can only be used in a non-static method. It is usually used in a virtual method override, but actually can be used to call any method in the base type. It is very different from normal method invocation because it circumvents the normal virtual-method dispatch: it calls the base method directly even if it is virtual.

like image 44
Timwi Avatar answered Sep 19 '22 18:09

Timwi