C#. Optional arguments. Advantages. Examples of using optional arguments. Ambiguity when using optional arguments

Optional arguments. Advantages. Examples of using optional arguments. Ambiguity when using optional arguments


Search other websites:

1. What are the optional arguments and optional parameters?

In a method declaration, some of its parameters may receive a default value. The parameter that receives the default value is called an optional parameter. A method that contains optional parameters in the declaration can be invoked without specifying arguments that correspond to these parameters. Arguments that are passed to the method and correspond to optional parameters are called optional arguments.

Thus, the arguments that are passed to the method are divided into mandatory arguments and optional arguments.
The general form of specifying an optional argument in the list of method parameters is:

type parametr_name = const_value


  • type – the type of optional parameter;
  • parameter_name – the name of the parameter that corresponds to the optional argument when calling the method;
  • const_value – a constant default value that is assigned to an optional parameter.

The general form of the method, which contains one optional parameter, is as follows:

access return_type MethodName(type parameter_name = const_value)
  // ...


  • access – method access modifier (private, protected, public);
  • return_type – the type returned by the method;
  • MethodName – the name of method;
  • parameter_name – the name of the parameter that corresponds to the default argument;
  • const_value – default value assigned to the parameter with the name parameter_name if the method MethodName() is called without parameters.

After such a declaration, you can call the MethodName() method in two ways:

  • using the given argument explicitly;
  • without using an argument. In this case, the parameter_name parameter will be assigned the default value.


2. The advantages of using the optional arguments

The use of optional arguments gives the following advantages:

  • it is not necessary to introduce additional “overloaded” the implementation of the method;
  • simplified call of complex methods or class constructors.

Arguments that are not specified when calling this method get the default value.


3. Examples of declaring and invoking methods that contain optional arguments

Example 1. Method that determines the volume of the sphere. The method takes one input parameter (radius of the sphere), which is an optional argument.

// method that contains an optional argument
double SphereVolume(double radius = 1.0)
  return 4.0 / 3.0 * 3.1415 * radius * radius * radius;

After such a declaration, the method can be called in two ways:

  • without using an explicit argument;
  • using an explicit argument.

The following program code demonstrates calling a method in various ways

// Demonstrate calling SphereVolume method
double vol;

// method call without explicit argument
vol = SphereVolume(); // vol = 4.188667

// method call with an explicit argument
vol = SphereVolume(3.0); // vol = 113.094

As can be seen from the above code, the first time the SphereVolume() method is called without an explicitly specified argument. In this case, nothing is passed to the method, and the internal parameter radius is set to the default value -1.0, which was specified when the method was declared.

The second time is invoked the method

vol = SphereVolume(3.0);

In this case, the argument 3.0 is explicitly passed to the method. The formal parameter radius of the method gets the value of the argument equal to 3.0. The default value is replaced with the new value.

Example 2. An implementation of a method that takes four optional parameters. The method can receive any number of optional parameters.
Below is the implementation of the LengthLine() method, which calculates the length of the segment. The method receives the coordinates of points:

  • x1, y1 – coordinates of the first point of the segment;
  • x2, y2 – coordinates of the second point of the segment.
// method determines the length of the segment
static float LineSegment(float x1 = 0, float y1 = 0, float x2 = 1, float y2 = 1)
  float length;
  length = (float)Math.Sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
  return length;

Using the method in other program code

// Demonstrate calling the LineSegment() method
float len;

// method call without explicit arguments
// arguments x1, y1, x2, y2 - are optional
len = LineSegment(); // x1=0, y1=0, x2=1, y2=1; len = 1.414214

// method call with 1 explicit argument
// arguments x1, y1, x2 - are optional
len = LineSegment(3); // x1=3, y1=0, x2=1, y2=1; len = 2.236068

// method call with 2 explicit arguments
// arguments x2, y2 - are optional
len = LineSegment(-1, 4); // x1=-1, y1=4, x2=1, y2=1; len = 3.605551


4. Examples of the implementation and use of classes that contain constructors with optional arguments

Example 1. A Triangle class is specified that implements a triangle on the plane. In the class are implemented:

  • six public variables with the names x1, y1, x2, y2, x3, y3. Variables implement the coordinates of the points that make up the triangle;
  • a constructor that takes optional arguments.

The program code of the Triangle class is as follows:

// a class that implements the triangle
class Triangle
  // coordinates of the points that form a triangle
  public double x1, y1, x2, y2, x3, y3;

  // class constructor gets optional arguments
  public Triangle(double x1 = 0, double y1 = 0, double x2 = 1, double y2 = 1, double x3 = -1, double y3 = -1)
    // initialization of class variables
    this.x1 = x1; this.y1 = y1;
    this.x2 = x2; this.y2 = y2;
    this.x3 = x3; this.y3 = y3;

Using a class in another program code may be as follows:

// Demonstrate the use of optional arguments in the constructor of the Triangle class
// 1. Explicitly pass all arguments to the class constructor
Triangle tr1 = new Triangle(2, 3, -1, -3, 0, 5); // x1=2, y1=3, x2=-1, y2=-3, x3=0, y3=5

// 2. Pass 5 arguments explicitly, argument y3 is an optional argument
Triangle tr2 = new Triangle(1, 2, 0, 0, -4); // x1=1, y1=2, x2=0, y2=0, x3=-4, y3=-1

// 3. Explicitly pass 2 arguments, x2, y2, x3, y3 are optional
Triangle tr3 = new Triangle(8, 9); // x1=8, y1=9, x2=1, y2=1, x3=-1, y3=-1

When creating an object of the Triangle class, a constructor is called that contains the default parameters. In the first case, a tr1 object is created. When an object is created, a constructor is called, to which all 6 explicitly given arguments (required arguments) are passed.
In the second case, when creating the tr2 object, a constructor is called in which 5 arguments are explicitly specified and one (y3) is an optional argument. In the method, the optional argument y3 is assigned a default value of -1.
In the third case, an object is created with the name tr3. When creating this object, the constructor gets the value of two explicitly specified arguments, the values of which are assigned to the variable parameters x1, y1. The other 4 parameters of the constructor get the default value, in this case x2 = 1, y2 = 1, x3 = -1, y3 = -1.

Example 2. Let the class ArrayInt be set that implements an array of integers. The class declares a constructor that contains optional arguments.

class ArrayInt
  int[] A;

  // constructor with optional argument n
  public ArrayInt(int n = 0)
    A = null;
    if (n == 0) return;

    // allocate memory for array A
    A = new int[n];

    // zeroing the array
    for (int i = 0; i < A.Length; i++)
      A[i] = 0;

  // array access methods
  public int[] Get() { return A; }

  public void Set(int[] AA)
    A = new int[AA.Length];
    for (int i = 0; i < A.Length; i++)
      A[i] = AA[i];

Using the class in another program code

// invoke the constructors with optional arguments
ArrayInt ai1 = new ArrayInt(); // constructor call with optional argument
ArrayInt ai2 = new ArrayInt(5); // constructor call with a required argument

// checking
int n_items;

if (ai1.Get() != null)
  n_items = ai1.Get().Length;
  n_items = 0; // n_items = 0

n_items = ai2.Get().Length; // n_items = 5


5. What requirements does C# syntax impose on the order in which optional arguments are declared in a method?

According to C# syntax, when using optional arguments in a method, you must adhere to the following rule:

  • the declaration of optional parameters must be implemented to the right of the required ones.


6. How many optional parameters can be declared in a method?

Any number of optional parameters can be declared in the method. The main thing is that their declaration should be to the right of the declaration of the required parameters.


7. Which elements of the C# programming language can use optional arguments?

Optional arguments can be used in:

  • class methods (including constructors);
  • class constructors;
  • delegates.


8. An example of using optional arguments in delegates

Delegates as well as methods can receive optional arguments. In this case, the delegate declaration syntax is the same as the method declaration syntax.
Let delegate TInt be given, which gets and returns an integer value. The delegate parameter is set to its default value, which is 1. There are also 3 methods, the signature of which coincides with the signature of the delegate.

// declaration of the type of the delegate TInt, receiving the default value = 1
delegate int TInt(int d = 1);

// method that multiplies an integer by 2
static int Mult2(int d)
  return d * 2;

// method that returns the square of an integer
static int Square(int d)
  return d * d;

// method of multiplying the number by 5
static int Mult5(int d)
  return d * 5;

The use of a TInt delegate that takes an optional argument can be as follows:

TInt t; // declare a delegate of type tInt

// create a chain of methods calls
t = Mult2; // t => Mult2
t += Mult5; // t => Mult2 => Mult5

// call successively methods
int result;

// method call Mult2(), Mult5() with optional argument
result = t(); // result = 5

// method call Mult2(3), Mult5(3) with an explicit argument
result = t(3); // result = 15


9. What does the term “ambiguity” mean when invoking optional arguments? Example

“Ambiguity” may occur when the “overload” method, which contains optional arguments. “Ambiguity” is manifested in cases where the compiler does not know which of the “overloaded” methods to call.

For example. Let two Sum() overloaded methods be given, taking optional arguments. In both methods, the first argument a, is required.

int Sum(int a, int b = 1, int c = 2)
  return a+b+c;

int Sum(int a, double b = 2.0, double c = 3.0)
  return (int)(a + b + c);

If you write the following code calling the Sum() method

int t;

// ambiguous call, the compiler does not know which method to call
t = Sum(5);

then the compiler will generate the error message:

The call is ambiguous between the following methods or properties:
'Sum(int, int, int)' and 'Sum(int, double, double)'


Related topics