base and this keyword in C#

Welcome to CodeSpread!

I have seen programmers getting confused with keywords like ‘base’ and ‘this’. Although self-explanatory, still requires basic knowledge of scope to dive in deep.

Let’s take them one by one.

base keyword:

So by name, we can easily deduce that it is related to inheritance and mainly revolves around base and derived class. Let’s see an example to understand more.

public class SiteName
{

public  virtual void SiteInfo()
{
Console.WriteLine("Name: CodeSpread");
}
}
class Domain: SiteName
{

public override string SiteInfo()
{
base.SiteInfo()
Console.WriteLine("domain: www.codespread.com");
}
}

I know that’s a not a so good example but still eligible. In the derived class, we were able to call the parent method by using ‘base’ keyword so we can define ‘base’ keyword as, freedom to access (method, property etc.) of the base class from within a derived class.

Note:

  • Keep your eyes open for override functionality.
  • It is an error to use the base keyword from within a static method.

this keyword:

‘this’ keyword is more or so related to the current instance of the class.

So why we need it? let’s say in simple words ‘ to avoid naming conflicts’.

Note: Static constructors and member methods do not have a ‘this’ keyword.

There are few common uses:

  1. Names ambiguity.
  2. Constructor to constructor call.
  3. Indexer

Names ambiguity.

class Employee
{
string EmployeeName;
public Employee(string EmployeeName)
{
this.EmployeeName=EmployeeName;//this will refer to current instance else EmployeeName will refer itself
}

Constructor to constructor call.

class Contractor
{
public Contractor():Employee("CodeSpread") //calls base constructor: Employee(string EmployeeName)
{
}
}

Indexers

class ClassCollections

{

static void Main(string[] args)

{

NewCollection newCollection = new NewCollection();

newCollection [0] = “Hello” ;

newCollection [1]= “World”;

Console.WriteLine(newCollection [0]+newCollection [1]);

}

}

Please share your views or feedback to admin@codespread.com

Leave a Reply

Your email address will not be published. Required fields are marked *

  1. thanks for the tutorial
    I am having a problem.
    The feature “Create SQL server database” isn’t available , I can’t select it.
    Can you help, please ?