CSharp - Constructor with Optional Parameters

Introduction

Consider the following program and output.

Demo

using System;

class Employee//  w w w  . j a v  a 2s .  c  o m
{
    public string Name;
    public int Id;
    public double Salary;
    public Employee(string name = "Anonymous", int id = 0, double salary = 0.01)
    {
        this.Name = name;
        this.Id = id;
        this.Salary = salary;
    }
}
class Program
{
    static void Main(string[] args)
    {
        Employee emp1 = new Employee("A", 1, 10000.23);
        Employee emp2 = new Employee("S", 2);
        Employee emp3 = new Employee("B");
        Employee emp4 = new Employee();

        Console.WriteLine("Employee Details:");
        Console.WriteLine("Name ={0} Id={1} Salary={2}", emp1.Name,
         emp1.Id, emp1.Salary);
        Console.WriteLine("Name ={0} Id={1} Salary={2}", emp2.Name,
         emp2.Id, emp2.Salary);
        Console.WriteLine("Name ={0} Id={1} Salary={2}", emp3.Name,
         emp3.Id, emp3.Salary);

        Console.WriteLine("Name ={0} Id={1} Salary={2}", emp4.Name,
            emp4.Id, emp4.Salary);
        Console.ReadKey();
    }

}

Result

Analysis

Here we have used the concepts of optional parameters in a constructor.

This constructor needs three arguments:

  • one for the employee's name,
  • one for the employee's ID, and
  • one for the employee's salary.

But if we pass fewer arguments, the compiler will not complain at all.

The code is picking the default values that we set in the optional parameter's list.

From the output, you can see that the default values of an employee object were Anonymous,0 and 0.01 corresponding to the employee's name, ID, and salary.

Related Topic