base keyword in C Sharp.

base keyword is used to refer the Base class member . Base class is also called as Parent class and Super class as well.

So when to use base Keyword.
> To access the base class method which is overridden in child class .
> If you want to access the base class constructor while creating the child class object .
Lets explain it an example.

Case-1 :

public class PersonDetails
{
    protected string name = "John";
    public virtual void GetInfo()
    {
        Console.WriteLine("MyName: {0}", name);
    }
}
class EmployeeDetails : PersonDetails
{
    public string empid = "AA23";
    public override void GetInfo()
    {
        base.GetInfo();
        Console.WriteLine("Employee ID: {0}", empid);
    }
}

class TestClass1
{
    static void Main()
    {
        EmployeeDetails Emp = new EmployeeDetails();
        Emp.GetInfo();
    }
}
/*
Output :
MyName: John
Employee ID: AA23
*/


Case -2:
public class BaseClass
{
    int no;
    public BaseClass()
    {
        Console.WriteLine("I am in BaseClass()");
    }

    public BaseClass(int j)
    {
        no = j;
        Console.WriteLine("I am in BaseClass(int j)");
    }

    public int GetNo()
    {
        return no;
    }
}

public class DerivedClass : BaseClass
{
    // This constructor will call BaseClass.BaseClass()
    public DerivedClass() : base()
    {
    }

    // This constructor will call BaseClass.BaseClass(int j)
    public DerivedClass(int j) : base(j)
    {
    }

    static void Main()
    {
        DerivedClass dd = new DerivedClass();
        DerivedClass cc = new DerivedClass(5);
    }
}
/*
Output:
I am in BaseClass()
I am in BaseClass(int j)
*/
Please like this article if it really helped you. 

Comments

Popular posts from this blog

Unable to load one or more breakpoints in Visual studio.

The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.

The transaction is aborted or Failure while attempting to promote transaction.