C# - Call Non-trailing Arguments as Default Argument

In this tutorial, we will learn how to call non-trailing arguments as default arguments in C#?
[Last updated : March 21, 2023]

As we know that, In C++ we can call only trailing argument as a default argument. But in C# we can call non-trailing argument as default argument. We can make only trailing argument as a default argument, but we can call non-trailing arguments.

Calling non-trailing arguments as default argument

To call non-trailing argument as a default argument, we need to use parameter name with colon operator (:).

C# program for calling non-trailing arguments as default argument

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

namespace ConsoleApplication1 {
  class EMP {
    private string name;
    private int age;
    private int salary;

    public void setEmp(string name, int a = 18, int salary = 20000) {
      this.name = name;
      this.age = a;
      this.salary = salary;
    }

    public void printEmp() {
      Console.WriteLine("\nEmployee Record: ");
      Console.WriteLine("\tName  : " + name);
      Console.WriteLine("\tAge   : " + age);
      Console.WriteLine("\tSalary: " + salary);
    }
  }
  
  class Program {
    static void Main() {
      EMP E1 = new EMP();

      E1.setEmp("Sandy", 25, salary: 48500);
      E1.printEmp();

      EMP E2 = new EMP();

      E2.setEmp("Mark", a: 33, 34000);
      E2.printEmp();
    }
  }
}

Output

Employee Record:
        Name  : Sandy
        Age   : 25
        Salary: 48500

Employee Record:
        Name  : Mark
        Age   : 33
        Salary: 34000

Explanation

In above program, we are creating a class named EMP, it contains method setEmp() which has two optional or default argument (age,salary).

With E1 object, we are using salary parameter with colon( : ) operator to assign value. While with E2 object we are using a parameter with colon( : ) to set age of employee.

C# Basic Programs »

Comments and Discussions!

Load comments ↻





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