Friday 12 April 2013

What is ParamArray Parameter in .Net

                      To allow the user  to pass any number of arguments of same data type to a parameter . We have to declare the parameter has an array. But when a parameter is declared as an Array then while calling the procedure, We must pass an array as argument and it is not possible to pass individual elements as arguments. To allow the user to pass an array of an argument or individual elements seperated with comma(,), we have to declare the parameter has ParamArray parameter.
                        To declare the parameter as ParamArray parameter , We have to prefix the parameter declaration with the keyword ParamArray .  ParamArray parameters have the following restriction.

  1. A procedure can have only one ParamArray Parameter
  2. ParamArray parameter must be last parameter in the parameter list.
  3. ParamArray parameter cannot be optional parameter.
  4. ParamArray parameter cannot be reference Parameter.
Example : The following example creates a Function with the name Sum that can accept any number of integers and returns their sum.

      Module  ParamArrayparameter
         Function Sum( Byval ParamArray A() as integer) As Integer
           Dim S as Integer
            For Each N as Integer in A 
           S+ =N
      Next
                     (OR)

       For Each N as Integer=0 in A.GetupperBound(0)
             Dim S as Integer
              S+ = A(i)
              Next
Return S
End Function

Sub Main()
Dim A() as integer = {1,2,3,4,5}
Console.WriteLine(Sum(A())
Console.WriteLine(Sum(A(22,33,44,5,55,22))
End Sub 
End Module.




  

           

                          

No comments:

Post a Comment