Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable number of arguments without boxing the value-types?

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.

like image 344
DxCK Avatar asked Dec 11 '09 21:12

DxCK


People also ask

What is variable number of argument?

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.

What is first parameter?

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.)


1 Answers

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.

like image 196
Reed Copsey Avatar answered Oct 04 '22 00:10

Reed Copsey