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.
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});
Except for:
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 });
}
}
}
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.
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.
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