Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#, Pass Array As Function Parameters

Tags:

python

c#

In python the * allows me to pass a list as function parameters:

def add(a,b): return a+b
x = [1,2]
add(*x)

Can I replicate this behavior in C# with an array?

Thanks.

like image 427
Mark Avatar asked Jan 07 '10 20:01

Mark


4 Answers

The params keyword allows something similar

public int Add(params int[] numbers) {
    int result = 0;

    foreach (int i in numbers) {
        result += i;
    }

    return result;
}

// to call:
int result = Add(1, 2, 3, 4);
// you can also use an array directly
int result = Add(new int[] { 1, 2, 3, 4});
like image 156
thecoop Avatar answered Oct 20 '22 01:10

thecoop


Except for:

  1. Changing the method signature to accept an array
  2. Adding an overload that accepts an array, extracts the values and calls the original overload
  3. Using reflection to call the method

then unfortunately, no, you cannot do that.

Keyword-based and positional-based parameter passing like in Python is not supported in .NET, except for through reflection.

Note that there's probably several good reasons for why this isn't supported, but the one that comes to my mind is just "why do you need to do this?". Typically, you only use this pattern when you're wrapping the method in another layer, and in .NET you have strongly typed delegates, so typically all that's left is reflection-based code, and even then you usually have a strong grip on the method being called.

So my gut reaction, even if I answered your question, is that you should not do this, and find a better, more .NET-friendly way to accomplish what you want.

Here's an example using reflection:

using System;
using System.Reflection;

namespace ConsoleApplication1
{
    class Program
    {
        public Int32 Add(Int32 a, Int32 b) { return a + b; }
        static void Main(string[] args)
        {
            Program obj = new Program();

            MethodInfo m = obj.GetType().GetMethod("Add");
            Int32 result = (Int32)m.Invoke(obj, new Object[] { 1, 2 });
        }
    }
}
like image 28
Lasse V. Karlsen Avatar answered Oct 20 '22 01:10

Lasse V. Karlsen


You could using reflection. However if it's a variable length all the time you might be better off using an array as your method defenition however you would still need to parse the list unless it's a basic need that can be handled by collection methods / array methods.

like image 41
Joshua Cauble Avatar answered Oct 20 '22 01:10

Joshua Cauble


I'm fairly sure you could use reflection to access your method, and then use Invoke, using your array as the parameter list. Kind of round-about, though.

like image 28
Sapph Avatar answered Oct 20 '22 00:10

Sapph