6

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?

4 Answers 4

12

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});
Sign up to request clarification or add additional context in comments.

Comments

9

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 });
        }
    }
}

4 Comments

Upvoted this one rather than the params solution because it more correctly matches the question. The params solution would be correct if the question asked how to convert a function such as "def add(*numbers):"
Thanks. This is closest to what I was looking for since I can not modify the method signature. Time to read up on C# and reflection, although, it sounds like I should just refactor my approach to this.
Only if you cannot change the signature, and only if you actually must pass the values as an array. Why are you doing this anyway?
@Lasse, to be honest I looking for a way to do because I thought the Python way is slick (and it would 'fit in' with some C# code I've already written). After reading your answer, though, I'm going to rewrite some things to avoid this whole mess. Thanks for the education.
2

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.