ParamArray (Use varargs Functions)
This page was last reviewed on Dec 16, 2021.
Dot Net Perls
ParamArray. This keyword allows a method to be called with an array of values that are specified directly (not in an explicit array). The values are placed into an array by the compiler.
For optimal performance, adding many overloaded methods is usually best. But ParamArray can be used in VB.NET programs where performance is not that important.
An example program. Let us examine a simple program that uses ParamArray. Notice how the ParamArray keyword comes first, then the array name with parentheses attached to it.
Here PrintValues receives a ParamArray. We can call it with zero, one or many arguments.
Warning For performance, avoiding ParamArray is often a better solution. An array is created for each call to a ParamArray method.
Result When PrintValues() is called, it receives its elements as an array and loops over them with For Each. It prints them to the console.
Module Module1 Sub PrintValues(ParamArray values() As Integer) ' Display Length of array. Console.WriteLine("Count: " + values.Length.ToString()) ' Loop over ParamArray values. For Each value As Integer In values Console.WriteLine(value) Next End Sub Sub Main() ' Use ParamArray method. PrintValues() PrintValues(1) PrintValues(10, 20, 30) End Sub End Module
Count: 0 Count: 1 1 Count: 3 10 20 30
Some notes. Performance is not everything. For simplicity, using ParamArray for a varargs Function is a good plan. Often the array overhead will not matter.
A review. ParamArray is the same construct as "params" in C#. Other languages have similar constructs, sometimes referred to as varargs for "variadic" or "variable" argument lists.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 16, 2021 (edit link).
© 2007-2024 Sam Allen.