C#. Access to elements of a base class from an inherited class. Keywords base, new. Examples

Access to elements of a base class from an inherited class. Keywords base, new. Examples


Contents


1. Keyword base. The purpose. When is the base keyword used?

The base keyword is relevant in cases where an inheritance relation is used between classes. Here it is possible that in the base and inherited classes there are methods (elements) with the same names and signatures. In this case, the element in the derived class hides the corresponding element of the base class. To access an element of a base class from an inherited class, you need to use the base keyword.

The base keyword is used in inherited classes in the following cases:

  • when from the constructor of a derived class you need to call the constructor of the base class. More details about this way of using base are described here;
  • when it is necessary to call a method of a base class from a method of a derived class, if this method is overrided;
  • when from a method of a derived class you need to access the data member of the base class. In this case, the data member can be declared with any access modifier except than private;
  • when you need to access a property of a base class from a method of a derived class (the property is not declared as private);
  • if it is necessary to emphasize (specify) that in this method of an inherited class elements of the base class are used.

 

2. Calling base class methods with base. General form. Example

Using the base keyword, you can access any elements of the base class that are not hidden (do not contain the private modifier).
The general form of using the base keyword to access the base class method is as follows:

base.Method();

where Method() – method of the base class. If the derived class does not have an implementation of the method named Method(), then using base is optional.

The general form of using the base keyword to access a data member (not a private data member)

base.variable;

where variable is the name of the data member of the base class.

 

3. Graphical explanation of access to elements using the base keyword

Figure 1 shows access to the elements of base class A from the method of the derived class B.

C#. Inheritance. Keyword base. Ways to access different elements of classes from method

Figure 1. Ways to access different elements of classes A, B from Method()

 



4. An example that demonstrates the use of the base keyword to access various elements of the base class

Let two classes A and B be given. The base class A contains the following elements:

  • internal field d with access modifier protected;
  • internal field a with access modifier private;
  • public method named Method1();
  • public property AA, which implements access to the internal field a.

Class B inherits from class A and contains the following elements:

  • internal field d with access modifier protected;
  • internal field b with access modifier private;
  • public method named Method1();
  • public property BB that accesses the internal field b.

The text of a program created using the Console Application template is as follows

using static System.Console;

namespace C_sharp
{
  // Class A - base for class B
  class A
  {
    // 1. Internal class fields
    protected int d;
    private int a;

    // 2. Class constructor
    public A()
    {
      // initializes fields with some values
      a = 10;
      d = 20;
    }

    // 3. public method of the class
    public void Method1()
    {
      WriteLine("A.Method1()");
    }

    // 4. public property - access to the field a
    public int AA
    {
      get { return a; }
      set { a = value; }
    }
  }

  // Class B - inherited from class A
  class B : A
  {
    // 1. Internal class fields
    // Field d hides class A field of the same name d
    protected int d;
    private int b;

    // 2. Class constructor
    public B()
    {
      d = 40;
      b = 50;
    }

    // 2. A method that overrides (hides) the Method1() of class A.
    // This method demonstrates access
    // to different elements of class A
    public void Method1()
    {
      WriteLine("B.Method1()");

      // 1. Invoke the Method1() of class A
      base.Method1();

      // 2. Invoke a property AA of class A
      int t = AA; // here you can without the word base
      WriteLine("A.AA = {0}", t);

      // 3. Access to the internal field d of class A
      t = base.d; // the field d of class A
      WriteLine("A.t = {0}", t);

      // 4. Access to field a of class A - forbidden
      // t = base.a; // запрещено, поле A.a есть private
    }

    // 3. public property BB
    public int BB
    {
      get { return b; }
      set { b = value; }
    }
  }

  class Program
  {
    static void Main(string[] args)
    {
      // Demonstration of using the base keyword
      // 1. Create an instance of class B
      B obj = new B();

      // 2. Invoke Method1() of class B,
      // this method uses elements of class A
      objB.Method1();
    }
  }
}

 

5. Access to base class properties using base keyword. Base class Circle and derived class Sector. Example

The example demonstrates access to the property of the base class. Two classes are specified: Circle – the base class, Sector – an inherited class from Circle. Both classes have the Area property. To call the Area property of the base class from the derived Sector class, you need to apply as follows

base.Area;

Below is the text of a program that demonstrates the use of the base keyword.

using System;
using static System.Console;

namespace C_sharp
{
  // The Circle class
  class Circle
  {
    // 1. Internal fields
    protected double radius; // radius
    protected double x, y; // coordinates of the centre

    // 2. Constructor
    public Circle(double _x, double _y, double _radius)
    {
      x = _x;
      y = _y;
      if (_radius <= 0)
        radius = 1.0;
      else
        radius = _radius;
    }

    // 3. Properties - access to the internal fields of the class
    public double X
    {
      get { return x; }
      set { x = value; }
    }

    public double Y
    {
      get { return y; }
      set { y = value; }
    }

    public double Radius
    {
      get { return radius; }
      set
      {
        if (value <= 0)
          radius = 1.0;
        else
          radius = value;
      }
    }

    // 4. Property Area - returns the area of a circle
    public double Area
    {
      get { return Math.PI * radius * radius; }
    }
  }

  // Class Sector - part of the circle
  class Sector : Circle
  {
    // 1. Internal field
    protected double alpha; // sector angle alpha = 0..360

    // 2. Constructor
    public Sector(double _x, double _y, double _radius, double _alpha) :
    base(_x, _y, _radius)
    {
      if ((_alpha >= 0) && (_alpha < 360))
        alpha = _alpha;
      else
        alpha = 0.0;
    }

    // 3. Property to access the internal field
    public double Alpha
    {
      get { return alpha; }
      set
      {
        if ((value >= 0) && (value < 360))
          alpha = value;
        else
          alpha = 0.0;
      }
    }

    // 4. A property that calculates the area of a sector,
    // invokes the same property of the base class
    public double Area
    {
      get
      {
        // Invoke a base class property
        return base.Area * alpha / 360;
      }
    }
  }

  class Program
  {
    static void Main(string[] args)
    {
      Sector sc = new Sector(1.5, 2.2, 3.0, 100);
      double x = sc.Area;

      // вывести площадь сектора
      WriteLine("Area of sector = {0:f3}", x);
    }
  }
}

As you can see from the above code, the Circle property is implemented in the base class Circle, which is used in the same property of the derived class Sector as follows

...

class Sector
{
  ...

  // 4. A property that calculates the area of a sector,
  // calls the same property of the base class
  public double Area
  {
    get
    {
      // Invoke a base class property
      return base.Area * alpha / 360;
    }
  }
}

...

 

6. The need to use the keyword new

The new keyword can be used in an inherited class before the name of an element that overrides (hides) the name of the base class. The use of the word new is recommended by the compiler in the case when it is necessary to emphasize that it is this method or property that overrides the method of the same name of the base class.
Figure 2 shows the use of the word new to override a method in a derived class.

C#. Inheritance. Ways to implement the method, which overrides base class method of the same name

Figure 2. Ways to implement the Method() method, which overrides
base class method of the same name

If you do not specify the new keyword in the method of the inherited class, then this will not affect the functionality of the program. However, in this case, the compiler will generate a warning:

B.Method hides inherited member A.Method. Use the new keywork if hiding was intended

In addition, the compiler will offer to correct this inaccuracy and, if necessary, will set the new keyword in the right place.

 


Related topics