Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to do something like this in C#?

Tags:

c#

parameters

Is there any way to do something like this in C#?

public void DoSomething(string parameterA, int parameterB)
{

}

var parameters = ("someValue", 5);
DoSomething(parameters);
like image 340
Alon Gubkin Avatar asked Apr 30 '10 13:04

Alon Gubkin


3 Answers

Close, but unfortuantely only using object (so you get lots of boxing/unboxing)

public void DoSomething(params object[] parameters)
{

}

var parameters = new object[]{"someValue", 5};
DoSomething(parameters); // this way works
DoSomething("someValue", 5); // so does this way
like image 170
Jamiec Avatar answered Nov 16 '22 04:11

Jamiec


Not today, no. We are at present prototyping exactly that feature for a possible hypothetical future version of C#.

If you can provide a really awesome reason why you want this feature, that would be points towards actually getting it out of prototyping and into a possible hypothetical future release. What's your awesome scenario that motivates this feature?

(Remember, Eric's speculations about possible hypothetical future releases of C# are for entertainment purposes only and are not to be construed as promises that there ever will be such a release or that it will have any particular feature set.)

like image 36
Eric Lippert Avatar answered Nov 16 '22 02:11

Eric Lippert


No need to use reflection if you first store as a delegate, but it does require a strong declaration of the delegate.

public void DoSomething(string parameterA, int parameterB)
{
    Console.WriteLine(parameterA+" : "+parameterB);
}
void Main()
{

    var parameters = new object[]{"someValue", 5};
    Action<string,int> func=DoSomething;
    func.DynamicInvoke(parameters);

}

...and you can forget about compile-time type/sanity checking of the parameter list. Probably a bad thing.

like image 22
spender Avatar answered Nov 16 '22 02:11

spender