Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolving params in C#

Tags:

c#

params

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?

like image 310
Spook Avatar asked Jun 17 '13 20:06

Spook


1 Answers

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

like image 128
Jon Avatar answered Oct 12 '22 20:10

Jon