C#, Pass Array As Function Parameters
c#, python
Solution
Except for:
- Changing the method signature to accept an array
- Adding an overload that accepts an array, extracts the values and calls the original overload
- 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 });
}
}
}
Problem
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.