Tuesday 26 November 2013

C#.NET - Optional Parameters

Optional Parameters:

Optional Parameters are introduced in C# 4.0 
A parameter is optional if it specifies a default value in its declaration.

Observe GetPerson method in the following class. In this method we are specifying pAddress and pSalary as optional arguments.

C#.NET


class Person
    {
        public string Name { get; set; }
        public string Address { get; set; }
        public decimal Salary { get; set; }

        public static Person GetPerson(string pName, string pAddress = "None Specified", decimal pSalary = 10000)
        {
            return new Person()
            {
                Name = pName,
                Address = pAddress,
                Salary = pSalary
            };
        }

    }

Whenever you call the GetPerson method without passing values to optional arguments (pAddress and pSalary) parameters will take the default values specified in the method declaration.

Observe the following 3 steps how we are calling GetPerson method using optional parameters

Step: 1
When you supply all parameters to GetPerson method it will give the person object with supplied values as follows.

C#.NET



Step: 2
When you supply only person name and address parameters to GetPerson method it will assign the person name and address with the values you supplied and salary(10000) will be assign to the default value.

C#.NET



Step 3:
When you supply only person name to GetPerson method it will assign the person name with the value you supplied and address (Hyderabad) and salary(10000) will be assign to the default values.

C#.NET

No comments: