Wednesday 15 July 2015

What is "base" keyword in C#?

The Base keyword is used to access member of the base class within a child class.

  • We can use to direct access of base class.
  • We can use as base constructor.
  • We can't use base class inside a static method.



base Keyword example:-

using System;

public class _Base // This is the base class.
{
    public _Base(int value)
    {
// Executes some code in the constructor.
Console.WriteLine("_Base constructor called");
    }
}

public class _Child : _Base // This class derives from the previous class.
{
    public _Child(int value)
: base(value)
    {
// The base constructor is called first.
// ... Then this code is executed.
Console.WriteLine("_Child constructor called");
    }
}

class Program
{
    static void Main()
    {
// Create a new instance of class _Base, which is the base class.
_Base a = new _Base(0);


// ... Then create an instance of _child.
// ... _Child executes the base constructor.
_Child b = new _Child(1);

    }
}

Output

_Base constructor called
_Base constructor called
_Child constructor called

These days we could see base keyword in entity framework.
using System.Data.Entity;

public class AccountsContext : DbContext
{
public AccountsContext(): base("name=DefaultConnection")
        {

        }
}


base. Example
public class Emp
{
    protected string id = "444-55-6666";
    protected string name = "John L. Raj";

    public virtual void GetInfo()
    {
        Console.WriteLine("Name: {0}", name);
        Console.WriteLine("SSN: {0}", id);
    }
}
class Employee : Emp
{
    public string id = "ABC567EFG";
    public override void GetInfo()
    {
        // Calling the base class GetInfo method:
        base.GetInfo();
        Console.WriteLine("Employee ID: {0}", id);
    }
}

class TestClass
{
    static void Main()
    {
        Employee E = new Employee();
        E.GetInfo();
    }
}
/*
Output
Name: John L. Raj
id: 444-55-6666
Employee ID: ABC567EFG
*/