0

My current issue is that I cannot use the method I wrote in the way I expected I could.

This is my signature :

IList<FileInfo> GetFiles(string name = "*", params SignalState[] states);

If relevant, please note that SignalState is an enum.

I would expect to be able to call this method with either one argument (string OR SignalState), none, or both of them. It works if I use both arguments, if I use none of them, or if I use only the name.

Right now I would expect that only providing a SignalState would work, because the compiler would assume the first parameter is optional and my SignalState fits the second parameter of the signature.

It does not work, and the error is quite clear, its expecting a name.

So I have tried changing the signature to this :

IList<FileInfo> GetFiles([Optional] string name, params SignalState[] states);

and obviously add a bit of logic to handle my wildcard default value for the string, but I still face the exact same problem.

I have also tried switching the two paramters, params SignalState first and the string last, but the compiler specifically says params should be last and shows an error in the signature.

Could someone explain to me why it is behaving the way it is ? I would expect to be able to jump to the second param since the first one is optional.

Is my only solution to implement as many overloads as necessary to be able to call my method with only a SignalState ? Or am I missing something in how optional parameters work ?

Gil Sand
  • 5,802
  • 5
  • 36
  • 78
  • As far as I am aware, optional parameters have to come last so you would need `IList GetFiles(params SignalState[] states, string name = "*");` – Deolus Apr 28 '20 at 14:08
  • I will add that to my question. I also had tried it and the compiler specifically said `params` should come last. – Gil Sand Apr 28 '20 at 14:09
  • @Deolus no, params have no be the last – Sohaib Jundi Apr 28 '20 at 14:10
  • 1
    Does this answer your question? [C# 4.0, optional parameters and params do not work together](https://stackoverflow.com/questions/3948971/c-sharp-4-0-optional-parameters-and-params-do-not-work-together) There are more existing threads with the similar problem, like [this](https://stackoverflow.com/questions/12747117/optional-argument-followed-by-params) or [this](https://stackoverflow.com/questions/15129296/params-parameter-with-default-parameter-values) – Pavel Anikhouski Apr 28 '20 at 14:14

0 Answers0