In ruby you can do something like this:
def method(a, b) ... end
myMethod(*myArray)
So if myArray had 2 items, it would be the equivalent of this:
myMehtod(myArray[0], myArray[1])
So that in the method body, a == myArray[0] and b == myArray[1]
Can you do this in C#? (So I can have a method declared with explicit arguments, instead of just taking an array as the argument)
EDIT: I should've been more specific about the method being called.
An array can be passed to functions in C using pointers by passing reference to the base address of the array, and similarly, a multidimensional array can also be passed to functions in C.
You can pass arrays to a method just like normal variables. When we pass an array to a method as an argument, actually the address of the array in the memory is passed (reference). Therefore, any changes to this array in the method will affect the array.
You can't pass arrays as function arguments in C. Instead, you can pass the address of the initial element and the size as separate arguments.
Syntax for Passing Arrays as Function Parameters The syntax for passing an array to a function is: returnType functionName(dataType arrayName[arraySize]) { // code } Let's see an example, int total(int marks[5]) { // code } Here, we have passed an int type array named marks to the function total() .
Your method can be declared to accept a parameter array, via params
:
void F(params int[] foo) {
// Do something with foo.
}
Now you can either pass a arbitrary number of int
s to the method, or an array of int
. But given a fixed method declaration, you cannot expand an array on-the-fly as you can in Ruby, because the parameters are handled differently under the hood (I believe this is different in Ruby), and because C# isn’t quite as dynamic.
Theoretically, you can use reflection to call the method to achieve the same effect, though (reflected method calls always accept a parameter array).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With