Friday 12 April 2013

What is Optional Parameter in .Net

                                 When a  procedure is created with  N number of parameters then while calling the procedure you must pass N number of arguments . When we want to allow the user to call procedure with variable number of arguments and not fixed number of argument then C++  provides the concept Default arguments and similar to this vb.net provides Optional Parameters.
                               To declare the parameters has Optional parameter use the keyword Optional. When  a parameter is declared with the keyword optional then it compulsory initialize it. The value to which it is initialized is called as default argument. When we are not passing argument for the optional parameter then default argument will be take. A rule to declare optional parameter is they must be last parameter in the parameter list.

Example : The following example creates a function with the name sum with five parameters but allows the user to call the function sum with two or three or four or five arguments

                Module OptionalParameters
           Function Sum(Byval  A as integer, Byval  b as integer, OPtional Byval  C as integer=0,OPtional Byval  D as integer=0 , OPtional Byval  E as integer=0) As integer
            Return A+B+C+D+E
End Function
Sub Main()
Console.WriteLine(sum(10,20))
Console.WriteLine(sum(10,20,30))
Console.WriteLine(sum(10,20,33,44))
Console.WriteLine(sum(10,20,33,44,32))
End Sub
End Module


No comments:

Post a Comment