C# - Optional Parameters Example

Here, we will learn about the optional parameters in C# with the help of example.
Submitted by Nidhi, on November 08, 2020 [Last updated : March 23, 2023]

Optional Parameter

An optional parameter contains the default value, if we did not pass any value for the optional parameter then the default value will be used inside the method. Here, will demonstrate the optional parameters in the method inside the class.

C# program to demonstrate the example of optional parameters

The source code to demonstrate the optional parameters is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# - Optional Parameters Example.

using System;

class Employee
{
    static public void PrintEmployee(int id, string name, int salary, string department="Account")
    {
        Console.WriteLine("Employee Details:");
        Console.WriteLine("\tEmployee Id        : " + id          );
        Console.WriteLine("\tEmployee Name      : " + name        );
        Console.WriteLine("\tEmployee Salary    : " + salary      );
        Console.WriteLine("\tEmployee Department: " + department  );
    }

 
    static public void Main()
    {
        PrintEmployee(101, "RAHUL", 10000, "HR"     );
        PrintEmployee(102, "ROHIT", 12000, "Sales"  );
        PrintEmployee(103, "VIRAT", 15000           );
        PrintEmployee(104, "MOHIT", 8000,  "Sales"  );
    }
}

Output

Employee Details:
        Employee Id        : 101
        Employee Name      : RAHUL
        Employee Salary    : 10000
        Employee Department: HR
Employee Details:
        Employee Id        : 102
        Employee Name      : ROHIT
        Employee Salary    : 12000
        Employee Department: Sales
Employee Details:
        Employee Id        : 103
        Employee Name      : VIRAT
        Employee Salary    : 15000
        Employee Department: Account
Employee Details:
        Employee Id        : 104
        Employee Name      : MOHIT
        Employee Salary    : 8000
        Employee Department: Sales
Press any key to continue . . .

Explanation

In the above program, we created the Employee class that contains two static methods PrintEmployee() and Main().

The PrintEmployee() method is used to print the employee details on the console screen. Here, we used the parameter department as an optional parameter. The default value of the department parameter is Account. In the PrintEmployeee() method, if we did not specify the department of the employee then Account is used as a department inside the PrintEmployee() method.

In the Main() method, we called the PrintEmployee() method, here, we did not pass any department for employee VIRAT then the department Account will be used inside the PrintEmployee() method.

C# Basic Programs »


Comments and Discussions!

Load comments ↻






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