What are the rules when resolving variable number of parameters passed by params
?
Suppose, that I have the code:
public void Method(params object[] objects) { }
public void Method(IMyInterface intf, params object[] objects) { }
How is Method(a, b, c)
resolved, if a is a IMyInterface? Can I be sure, that C# will always try to select most matching overload?
This is answered by the C# language spec:
7.5.3.1 Applicable function member
[...]
Otherwise, if MP is applicable in its normal form and MQ has a params array and is applicable only in its expanded form, then MP is better than MQ.
Otherwise, if MP has more declared parameters than MQ, then MP is better than MQ. This can occur if both methods have
params
arrays and are applicable only in their expanded forms.[...]
In your example both overloads would be applicable only in their expanded forms. Since the second has more declared parameters it would be better.
In the context of the spec, one overload being better than all the others means that the compiler selects it to bind the call, as would happen in the example under discussion (if no one overload is better than all the others, the result is a compile-time error due to ambiguity).
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