56

Thus for used base class for some commom reusable methods in every page of my application...

public class BaseClass:System.Web.UI.Page
{
   public string GetRandomPasswordUsingGUID(int length)
   {
      string guidResult = System.Guid.NewGuid().ToString();
      guidResult = guidResult.Replace("-", string.Empty);
      return guidResult.Substring(0, length);
   }
}

So if i want to use this method i would just do,

public partial class forms_age_group : BaseClass
{
      protected void Page_Load(object sender, EventArgs e)
      {
            //i would just call it like this
            string pass = GetRandomPasswordUsingGUID(10);
      }
}

It does what i want but there is a "Base" keyword that deals with base class in c# ... I really want to know when should use base keyword in my derived class....

Any good example...

BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
ACP
  • 34,682
  • 100
  • 231
  • 371

10 Answers10

81

The base keyword is used to refer to the base class when chaining constructors or when you want to access a member (method, property, anything) in the base class that has been overridden or hidden in the current class. For example,

class A {
    protected virtual void Foo() {
        Console.WriteLine("I'm A");
    }
}

class B : A {
    protected override void Foo() {
        Console.WriteLine("I'm B");
    }

    public void Bar() {
        Foo();
        base.Foo();
    }
}

With these definitions,

new B().Bar();

would output

I'm B
I'm A
Matti Virkkunen
  • 63,558
  • 9
  • 127
  • 159
  • 9
    It's not limited to functions. Wherever there is ambiguity in classes (parent and children), base keyword clarifies which method/data member the user is talking about. – Nayan Apr 15 '10 at 11:20
  • Would `A.Foo()` do the same thing as `base.Foo()`? – Kyle Delaney Feb 02 '17 at 21:05
  • 3
    @KyleDelaney No, A.Foo() is a static method call. Since A.Foo() is not static, you'll get an error if you did this. – krowe2 Sep 12 '17 at 14:33
  • You can add `base.Foo();` in the overridden method to call it as well. – wlwl2 Nov 09 '20 at 05:16
15

You will use base keyword when you override a functionality but still want the overridden functionality to occur also.

example:

 public class Car
 {
     public virtual bool DetectHit() 
     { 
         detect if car bumped
         if bumped then activate airbag 
     }
 }


 public class SmartCar : Car
 {
     public override bool DetectHit()
     {
         bool isHit = base.DetectHit();

         if (isHit) { send sms and gps location to family and rescuer }

         // so the deriver of this smart car 
         // can still get the hit detection information
         return isHit; 
     }
 }


 public sealed class SafeCar : SmartCar
 {
     public override bool DetectHit()
     {
         bool isHit = base.DetectHit();

         if (isHit) { stop the engine }

         return isHit;
     }
 }
Michael Buen
  • 38,643
  • 9
  • 94
  • 118
  • +1 for if(isHit) {remove the i and it takes on a whole different meaning} ;) – andrewWinn Apr 15 '10 at 12:17
  • 1
    @andrewWinn: that could be the primary reason why C# language designers cannot introduce VB.NET's IsNot keyword to C# language. It will have an appearance of booger :-D heheh – Michael Buen Apr 24 '10 at 05:33
8

If you have the same member in a class and its base class then the only way to call a member of the base class is the using base keyword:

protected override void OnRender(EventArgs e)
{
   // do something

   base.OnRender(e);

   // just OnRender(e); will cause StakOverFlowException
   // because it's equal to this.OnRender(e);
}
abatishchev
  • 98,240
  • 88
  • 296
  • 433
6

The real purpose of the “base” keyword in c# is as follows: suppose you want to call only the parent class' parameterized constructor - then you can use base and pass the parameters, please see below example...

Example -

 class Clsparent
{
    public Clsparent()
    {
        Console.WriteLine("This is Clsparent class constructor");
    }
    public Clsparent(int a, int b)
    {
        Console.WriteLine("a value is=" + a + " , b value is=" + b);
    }
}
class Clschild : Clsparent
{
    public Clschild() : base(3, 4)
    {
        Console.WriteLine("This is Clschild class constructor");
    }
}
class Program
{
    static void Main(string[] args)
    {
        Clschild objclschild = new Clschild();
        Console.Read();
    }
}
Martin Reiche
  • 1,642
  • 1
  • 16
  • 27
Ajay Kaushik
  • 91
  • 1
  • 1
4

The base keyword is used to access members in the base class that have been overridden (or hidden) by members in the subclass.

For example:

public class Foo
{
    public virtual void Baz()
    {
        Console.WriteLine("Foo.Baz");
    }
}

public class Bar : Foo
{
    public override void Baz()
    {
        Console.WriteLine("Bar.Baz");
    }

    public override void Test()
    {
        base.Baz();
        Baz();
    }
}

Calling Bar.Test would then output:

Foo.Baz;
Bar.Baz;
Will Vousden
  • 32,488
  • 9
  • 84
  • 95
4

Base is used in two ways.

  1. Base with functions
  2. 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.

  1. In the following example console prints..

parameter is 1, This is child constructor

  1. 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.

  1. 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

Don Dilanga
  • 2,722
  • 1
  • 18
  • 20
1

Base is used when you override a method in a derived class but just want to add additional functionality on top of the original functionality

For example:

  // Calling the Area base method:
  public override void Foo() 
  {
     base.Foo(); //Executes the code in the base class

     RunAdditionalProcess(); //Executes additional code
  }
Jasper
  • 451
  • 3
  • 7
0

You can use base to fill values in the constructor of an object's base class.

Example:

public class Class1
{
    public int ID { get; set; }
    public string Name { get; set; }
    public DateTime Birthday { get; set; }

    public Class1(int id, string name, DateTime birthday)
    {
        ID = id;
        Name = name;
        Birthday = birthday;
    }
}

public class Class2 : Class1
{
    public string Building { get; set; }
    public int SpotNumber { get; set; }
    public Class2(string building, int spotNumber, int id, 
        string name, DateTime birthday) : base(id, name, birthday)
    {
        Building = building;
        SpotNumber = spotNumber;
    }
}

public class Class3
{
    public Class3()
    {
        Class2 c = new Class2("Main", 2, 1090, "Mike Jones", DateTime.Today);
    }
}
Jon
  • 5,956
  • 10
  • 39
  • 40
0

Generally, we are using the base class to reuse the property or methods in child class of the base class, so we no need to repeat the same property and methods again in the child class.

Now, we use the base keyword to call a constructor or method from base class directly.

Example

public override void ParentMethod() 
  {
     base.ParentMethod(); //call the parent method

     //Next code.
  }

2) Example

class child: parent
{
    public child() : base(3, 4) //if you have parameterised constructor in base class
    {

    }
}
Janmejay Kumar
  • 309
  • 2
  • 7
0

Child class constructor calls parent class constructor implicitly if parent class constructor is parameter less, where if parent class constructor is parameterized it's programmers responsibility to called parent class constructor explicitly, so programmer has to pass the value to the parameter and for that we use base keyword.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Constructors
{   
    public class Class1 
    {
        public Class1(int i)
        {
            Console.WriteLine(i);

        }
    }
   
    public class Class2: Class1
    {
        public Class2():base(10)
        {
            Console.WriteLine("Used base key word to provied the value to the base class constructor");
       
        }
        static void Main()
        {
            Class2 obj = new Class2(); 
        }
    }
}

output is

10

"Used base key word to provied the value to the base class constructor"

derloopkat
  • 6,232
  • 16
  • 38
  • 45