I've read a number of articles on SoF about this, but funny enough, I feel that there is not concise answer. Maybe I just haven't found the correct post yet.
I want to know the best way on how to distinguish between multiple optional parameters when calling your c# console app.
Eg. Calling MyApp value1 [value2] [value3] [value4] [value5]
This app can be called by using 0 - n of the optional arguments like:
c:\MyApp.exe value1 value2 value3
c:\MyApp.exe value1 value4 value5
c:\MyApp.exe value1 value4
etc...
I can extract the arguments with
var argValue = args[1]
but how can I know which of all these optional arguments were actually used?
Should I just prefix them with a predefined label like:
c:\MyApp.exe value1 myArg4:value4 myArg5:value5
Yes, you need to provide some way of saying which value is which - just like you would for named arguments in a method call. The common conventions are:
--myArg4=value4
--myArg4 value4
(Some tools prefer --
, others prefer -
.)
There isn't anything built into the framework to do this very simply, but the commandline library is very easy to include (just as a source inclusion - you don't need it to be a separate class library). We use this for Noda Time for all our command-line tools.
In my experience, it's relatively rare to have named command-line parameters which can also be specified without the names. So while arguably you could infer from the fact that there are five values that they're just the five values in the right order, it's more common to just require names for everything.
In your case, it looks like value1
is always required, so could be inferred to be the value for any unnamed argument... but I don't know if commandline supports that use case - you'd need to look into it.
See more on this question at Stackoverflow