public void DoSomething(params object[] args)
{
// ...
}
The problem with the above signature is that every value-type that will be passed to that method will be boxed implicitly, and this is serious performance issue for me.
Is there a way to declear a method that accepts variable number of arguments without boxing the value-types?
Thanks.
To call a function with a variable number of arguments, simply specify any number of arguments in the function call. An example is the printf function from the C run-time library. The function call must include one argument for each type name declared in the parameter list or the list of argument types.
The first parameter in the class method is the class on which you are calling the method, not (necessarily) the class that defines the method. (Having a variable that always holds the same class would probably not be that useful.)
You can use generics:
public void DoSomething<T>(params T[] args)
{
}
However, this will only allow a single type of ValueType to be specified. If you need to mix or match value types, you'll have to allow boxing to occur, as you're doing now, or provide specific overloads for different numbers of parameters.
Edit: If you need more than one type of parameter, you can use overloads to accomplish this, to some degree.
public void DoSomething<T,U>(T arg1, params U[] args) {}
public void DoSomething<T,U>(T arg1, T arg2, params U[] args) {}
Unfortunately, this requires multiple overloads to exist for your types.
Alternatively, you could pass in arrays directly:
public void DoSomething<T,U>(T[] args1, U[] args2) {}
You lose the nice compiler syntax, but then you can have any number of both parameters passed.
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