Overloading of methods in classes. Examples The advantage of methods overloading. Constructors overloading

Overloading of methods in classes. Examples The advantage of methods overloading. Constructors overloading


Contents


 1. What is the essence of method overloading in a class?

The C# programming language allows class method overloading. Overloading means using the same name for different methods. In fact, the name of the method is overloaded.

Method overloading is a software implementation of several methods for which the following conditions are met:

  • all overloaded methods are of the same name;
  • overloaded methods differ in parameters. More precisely, the parameter type or the number of parameters in an overloaded methods should differ.

Method overloading in a class is the declaration of another method with the same name in the class but with different parameters. The parameters of the overloaded method must be different in type or quantity.

If an overloaded method is called, the compiler chooses the variant of the method whose parameters match (by type and quantity) with the arguments that are passed to the method.

 

2. What is a method signature? What are the requirements for method signature in terms of overloading?

The method signature is the name of the method and its parameter list. From an overload point of view, the following requirement applies to the method signature:

  • in one class there should not be two methods with the same signature.

 

3. Are two methods considered to be overloaded, that have the same parameters but return different values?

No, they are not. It’s error. According to C# syntax, overloaded methods must accept different parameters.

 

4. Examples of overloaded methods

Example 1. The MaxMethods class declares an overloaded Max() method that has 3 implementations. The method implements the search for a maximum between a different number of parameters of type int.

// overloading the Max() method in the MaxMethods class
class MaxMethods
{
  // overloaded Max() methods
  public int Max(int a, int b)
  {
    if (a < b) return b;
    return a;
  }

  public int Max(int a, int b, int c)
  {
    int max = a;
    if (max < b) max = b;
    if (max < c) max = c;
    return max;
  }

  public int Max(int a, int b, int c, int d)
  {
    int max = a;
    if (max < b) max = b;
    if (max < c) max = c;
    if (max < d) max = d;
    return max;
  }
}

The use of overloaded Max() method in the MaxMethods class is given below.

MaxMethods mm = new MaxMethods();
int max;

max = mm.Max(5, 6); // max=6 - method Max() with 2 parameters
max = mm.Max(1, -3, 8); // max=8 - method Max() with 3 parameters
max = mm.Max(2, 3, 5, 1); // max=5 - method Max() with 4 parameters

Example 2. In the AverageMethods class, the Average() method is declared, which receives an array of numbers and determines the arithmetic average of the array. The method has 2 overloaded implementations for types int and float. The number of parameters in the overloaded Average() methods is the same, however, the types of parameters differ.

// overloading the Average() method in the AverageMethods class
class AverageMethods
{
  // implementation of the Average() method for the array of int[]
  public double Average(int[] Array)
  {
    double avg, sum=0;
    for (int i = 0; i < Array.Length; i++)
      sum += Array[i];
    avg = (double)sum / Array.Length;
    return avg;
  }

  // implementation of the Average () method for the array of float[]
  public double Average(float[] Array)
  {
    double avg, sum = 0;
    for (int i = 0; i < Array.Length; i++)
      sum += Array[i];
    avg = (double)sum / Array.Length;
    return avg;
  }
}

The following demonstrates the use of the overloaded Average() method

AverageMethods am = new AverageMethods();
double avg;

int[] A = new int[10];
float[] B = new float[10];

for (int i = 0; i < A.Length; i++)
{
  A[i] = i;
  B[i] = i * i;
}

// invoke the method Average(int[] Array)
avg = am.Average(A); // avg = 4.5

// invoke the method Average(float[] Array)
avg = am.Average(B); // avg = 28.5

As you can see from the example, the compiler automatically determines the method to be called based on the type of its parameters.

 

5. What are the features of overloaded methods that accept parameters with ref and out modifiers?

If you try to declare different implementations of a method that contains the same parameters differing only by the ref and out modifiers, the compiler will generate an error.

For example. Suppose you need to implement two methods GetPi(), which return a number π of type double. With the following declaration of these methods in some class

class SomeClass
{
  // GetPi() methods differ by ref and out modifiers
  public void GetPi(ref double x)
  {
    x = 3.1415;
  }

  public void GetPi(out double x)
  {
    x = 3.1415;
  }
}

and compilation attempt, the compiler will generate an error message

SomeClass cannot define an overloaded method that differs only on parameter modifiers 'out' and 'ref'

This means that the ref and out modifiers do not change the overall method signature.

 

6. What are the advantages of methods overloading?

Overloading of methods provides the following advantages:

  • there is no need to declare additional methods with different names to perform similar work. This simplifies and reduces the program code, which in turn leads to an increase in the readability of the program;
  • the basic principle of polymorphism is implemented – one interface, many methods. This is convenient when one method is addressed using the same name, and the compiler chooses method implementation, depending on the parameters;
  • convenient access to related methods based on a common name is provided;
  • overloaded methods can perform completely different work, that is, have completely different program code. It all depends on the parameters received. However, it is advisable (recommended) that overloaded methods do the same work.

 

7. Overloading constructors in class. Examples

Class constructors can be overloaded just like methods. The class declares two overloaded constructors.

// class that implements a point on the coordinate plane
class CPoint
{
  double x, y; // internal class variables

  // overloaded class constructors
  // constructor without parameters
  public CPoint()
  {
    x = y = 0.0;
  }

  // constructor accepts 2 parameters of type double
  public CPoint(double xx, double yy)
  {
    x = xx;
    y = yy;
  }

  // constructor accepts 2 parameters of type int
  public CPoint(int xx, int yy)
  {
    x = xx;
    y = yy;
  }

  // access methods
  public void SetXY(double xx, double yy)
  {
    x = xx;
    y = yy;
  }

  public void GetXY(out double xx, out double yy)
  {
    xx = x;
    yy = y;
  }
}

The following demonstrates the use of overloaded class constructors.

// constructors overloading
CPoint pt1 = new CPoint(); // call the constructor without parameters
CPoint pt2 = new CPoint(2.5, 3); // constructor call with double parameters
CPoint pt3 = new CPoint(7, 5); // constructor call with int parameters

double x, y;

pt1.GetXY(out x, out y); // x = 0; y = 0
pt2.GetXY(out x, out y); // x = 2.5; y = 3
pt3.GetXY(out x, out y); // x = 7; y = 5

Example 2. A Circle class is specified that implements a circle on the coordinate plane of a given radius. In class are implemented 4 constructors that accept different number of parameters. The program code of Circle class is as follows:

// class that implements a circle
class Circle
{
  int x, y;
  int radius;

  // overloaded constructors of class
  // constructor without parameters
  public Circle()
  {
    x = y = 0;
    radius = 1;
  }

  // constructor with 1 parameter
  public Circle(int radius)
  {
    x = y = 0;
    this.radius = radius;
  }

  // constructor with 2 parameters
  public Circle(int x,int y)
  {
    this.x = x;
    this.y = y;
    radius = 1;
  }

  // constructor with 3 parameters
  public Circle(int x, int y, int radius)
  {
    this.x = x;
    this.y = y;
    this.radius = radius;
  }

  // access methods
  public void Get(out int x, out int y, out int radius)
  {
    x = this.x;
    y = this.y;
    radius = this.radius;
  }
}

Below code demonstrates the use of overloaded constructors of class

// call of different overloaded constructors of class Circle
// call of constructor without parameters
Circle c1 = new Circle(); // x = 0; y = 0; radius = 1;

// call of constructor with 1 parameter
Circle c2 = new Circle(5); // x = 0; y = 0; radius = 5;

// call of constructor with 2 parameters
Circle c3 = new Circle(2, 4); // x = 2; y = 4; radius = 1;

// call of constructor with 3 parameters
Circle c4 = new Circle(3, 5, 7); // x = 3; y = 5; radius = 7;

 

8. How is implemented the call of overloaded constructor using the ‘this’ keyword? General form

C# allows you to call one constructor from another when there are several overloaded constructor implementations in the class. To call another overloaded constructor from the given constructor, use the ‘this’ keyword. The general form of such a call is as follows.

constructor_name(parameters1) : this(parameters2)
{
  // ...
}

where

  • constructor_name – the name of the constructor that calls the overloaded constructor;
  • parameters1 – constructor parameters that call the overloaded constructor. This constructor is invoked the second after invoking the constructor denoted by the ‘this’ keyword;
  • parameters2 – the parameters of the overloaded constructor, which is spicified by the keyword ‘this’. This constructor is invoked first.

 

9. An example of calling an overloaded constructor using the keyword this

Example. An implementation of the CPixel class, which describes a pixel on a monitor screen. A pixel is characterized by the following parameters:

  • integer coordinates x, y;
  • a color.

The class that contains 2 overloaded constructors. The class demonstrates a call of overloaded constructor.

class Pixel
{
  // internal variables
  int x, y;
  int color;

  // class constructors
  // constructor with 1 parameter
  public Pixel(int _color)
  {
    x = y = 0;
    color = _color;
  }

  // constructor with 3 parameters - a calling the another constructor from a constructor
  public Pixel(int _x, int _y, int _color) : this(_color)
  {
    x = _x;
    y = _y;
  }

  // method of reading internal variables
  public void Get(out int _x, out int _y, out int _color)
  {
    _x = x;
    _y = y;
    _color = color;
  }
}

The call of the overloaded constructor is done with the next code.

...

public Pixel(int _x, int _y, int _color) : this(_color)
{
  x = _x;
  y = _y;
}

...

Constructor with 3 parameters calls a constructor with 1 parameter. With such a call, the parameter that is in the calling constructor must necessarily be in the called constructor (constructor with keyword ‘this’). In our case, the _color parameter is required.

Demonstrating the use of the Pixel class

// constructor call from another constructor
Pixel px = new Pixel(2, 5, 10); // the constructor with 3 parameters is called
int x, y, color;

px.Get(out x, out y, out color); // x = 2; y = 5; color = 10;


Related topics