r3plica
r3plica

Reputation: 13397

Function as parameter with params arg

I have a function with this signature:

public static async Task LoadAsync<T>(T model, Func<T, PropertyInfo, Task> comparer, params string[] includes) where T: class

which I invoke like this:

await EagerLoader.LoadAsync(model, SetPropertyValue, includes);

The SetPropertyValue is the function that I pass to LoadAsync. It's signature is like this:

private async Task SetPropertyValue(Account model, PropertyInfo property)

What I would like to do is change that signature to this:

private async Task SetPropertyValue(Account model, PropertyInfo property, params string[] includes)

How do I represent that in my LoadAsync signature?

Upvotes: 1

Views: 75

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727067

params qualifier is not part of the type. At run-time, its presence is represented as an attribute [ParamArray] on the definition of your method's parameter.

If you change the type to

Func<T, PropertyInfo, string[], Task>

you would be able to pass both

Task SetPropertyValue(Account model, PropertyInfo property, params string[] includes)

and

Task SetPropertyValue(Account model, PropertyInfo property, string[] includes)

(i.e. with and without params). Since params is not part of the parameter type, string[] cannot be classified as params in the type arguments of the Func generic delegate.

This should work fine in your use case, because your LoadAsync will not need to invoke the comparer delegate using the variable-argument syntax, i.e. LoadAsync would be passing the whole array, rather than a variable-length list of strings that the compiler must combine into an array.

Upvotes: 1

Related Questions