views:

109

answers:

4

I've been developing .net console applications using C# and have always just dictated what order parameters must be inserted in so that args[0] is always start date and args[1] is always end date, for example.

however I would like to move over to using named parameters so that any combination of parameters can be sent in any order, such as the typical "-sd" would prefix a start date.

I know I could parse through the args[] looking for "-" and then read the name and look the next position for the accompanying value, but before doing that wanted to see if there was any kind of baked in handling for this rather standard practice.

is there something like this out there already that could do as such:

DateTime startDate = (DateTime)((ConsoleParameters)args[])["sd"]

I'm using C# and .Net 4

+2  A: 

There is nothing built into the core framework.

A lot of people thing NDesk.Options is useful for this sort of thing. Check out this example (taken directly from the provided link):

string data = null;
bool help   = false;
int verbose = 0;

var p = new OptionSet () {
    { "file=",      v => data = v },
    { "v|verbose",  v => { ++verbose } },
    { "h|?|help",   v => help = v != null },
};
List<string> extra = p.Parse (args);
Larsenal
NDesk.Options appears to be just the sort of thing I was looking for in lieu of a method built into .net. Thanks.
kscott
+1  A: 

You can use NDesk.Options.

SLaks
+3  A: 

Yes, the "magic" is that this is a common problem and it has been adequately solved. So I recommend using an already written library to handle parsing command line arguments.

CommandLineParser has been great for me. It is reasonably documented and flexible enough for every type of command line argument I've wanted to handle. Plus, it assists with usage documentation.

I will say that I'm not the biggest fan of making a specific class that has to be adorned with attributes to use this library, but it's a minor point considering that it solves my problem. And in reality forcing that attributed class pushes me to keep that class separate from where my app actually retrieves it's settings from and that always seems to be a better design.

qstarin
A: 

There is no such a thing as named parameters. "-sd" is just a choice for a specific application. It can be "/sd" as well. Or "sd=". Or whatever you want.

Since there are no named parameters, there is nothing inside .NET Framework which let you use the "-sd" syntax.

But you can quite easily build your own method to get a set of "named parameters" for your app.

Edit: or, even better, you can use an existing library, like suggested in other answers.

Edit: reading the answer by @Sander Rijken, I see that I was wrong: there were still an implementation of "-sd" syntax in .NET 4.0 before the release. But since it was dropped before the final release, the only ways are still to create your own method or to use an existing library.

MainMa