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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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: