C# - Default Arguments

In this tutorial, we will learn about the default or optional arguments in C# with the help of example.
[Last updated : March 21, 2023]

What are Default Arguments?

C#.Net has the concept of Default Arguments, which are also known as Optional Arguments in C#.

Understand the concept of Default Arguments by these points:

  1. Every default argument contains a default value within the function definition.
  2. If we do not pass any argument for default argument then, it uses default value.
  3. Given default value for default argument must be a constant.
  4. Default argument cannot be used for constructor and indexer etc.

Syntax to define default arguments

public void Method_Name(int required_arg, 
    string optionalstr = "default string value",
    int optionalint = 10)

C# example for default arguments

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1 {
  class Demo {
    private int a, b, c;

    //function definition with default arguments
    public void setValue(int X, int Y = 10, int Z = 20) {
      a = X;
      b = Y;
      c = Z;
    }

    //printing the values
    public void printValue() {
      Console.WriteLine("Values are : " + a + ", " + b + ", " + c);
    }

  }

  class Program {
    static void Main() {
      Demo D = new Demo();

      //passing one argument other will be assigned
      //with default arguments
      D.setValue(5);
      D.printValue();
      //passing two arguments other will be assigned
      //with default arguments
      D.setValue(5, 8);
      D.printValue();
      //passing all arguemnts
      D.setValue(5, 8, 13);
      D.printValue();
    }
  }
}

Output

Values are : 5, 10, 20
Values are : 5, 8, 20
Values are : 5, 8, 13

Explanation

In the above program, the method setValue() has a default or optional argument which is z, and we're assigning its default value of 20. When this argument is not specified during the method call, the value 20 will be used. And if the method is called with a new value then a new value will be used.

C# Basic Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.