Base is used in two ways.
- Base with functions
- Base with variables.
Base with functions
When base is used with functions the purpose of it is to call the parent class with parameters when parent class is inherited by the child class. I will explain that with an example.
- In the following example console prints..
parameter is 1,
This is child constructor
- Now if you removed base(parameter), then console prints..
This is Parent Constructor,
This is child constructor
When you instantiate an object from child class, the constructor is called as soon as it's instantiated. When you inherit the parent class from child class, both constructors in parent, and child classes are called because both are instantiated. When using base() you directly call the constructor in the parent class. So if it says base(), it means the constructor in parent class without any parameters, when using base(parameter), it means the constructor in the parent class with a parameter. This is a sort of function overloading. The type of parameter variable used inside of the base() brackets is defined by parameters list of the function used with base (in the following instance it's child(int parameter))
using System;
class Parent
{
public Parent()
{
Console.WriteLine("This is Parent Constructor");
}
public Parent(int parameter)
{
Console.WriteLine("parameter is " + parameter);
}
}
class Child : Parent
{
public Child(int parameter): base(parameter)
{
Console.WriteLine("This is child constructor");
}
}
class Program
{
static void Main(string[] args)
{
Child childObject = new Child(1);
}
}
Demo
https://repl.it/@donqq/baseKeyword#main.cs
Base with variables.
- In the following example, console prints..
Parent, Child.
In the following example, if you use base keyword, it means you address to the parent class inherited by the child class. If you use this, you address to the class itself, which means the child class as you instantiated the child class, and thereby calling its constructor. So when you use base.value it means you refer to the variable in the parent class, and when you refer to the this.value it means you refer to the variable in the child class. You can distinguish to which variable you refer to with this base, this keywords when both have same names. remember you can't use base, this keywords in the class outside of a function. You have to use them inside of a function to refer to a variable initialised in the global level. Also you can't use them to refer to a local variable initialised inside of a function.
using System;
class Parent
{
public string value = "Parent";
}
class Child : Parent
{
public string value = "Child";
public Child() {
Console.WriteLine(base.value);
Console.WriteLine(this.value);
}
}
class Program
{
static void Main(string[] args)
{
Child childObject = new Child();
}
}
Demo
https://repl.it/@donqq/Base-Class