Saturday, February 21, 2009

Command Line Parsing – A wheel we can finally stop reinventing with .Net 4.0

B# .NET Blog - .NET 4.0 – System.Shell.CommandLine Parsing – Part 1

“Introduction

Command-line parsing isn’t a trivial thing and the wheel has been reinvented many times to make this job easier. Starting with .NET 4.0 though, developers will have built-in support for command-line parsing in the framework. In this series of posts I’ll dive into the details of this hidden treasure in .NET Framework 4.0. You can actually start playing with it today, by downloading the Visual Studio 2010 and .NET Framework 4.0 CTP.

So, what’s the deal? Why focus on something seemingly old-fashioned like command-line parsing? Turns out quite some programs want to support command-line arguments of some sort, no matter whether the tool is intrinsically command-line driven (e.g. console applications such as compilers) or comes with a GUI: they all have a Main method. And that’s where the pain starts. All you get from Main’s arguments is an array of strings, and you’re on your own from there on. The very first thing you’re likely going to do is some kind of parsing to turn the arguments into rich objects. Far from trivial if you even think about a little bit of flexibility at the command-line:

  • is the argument required or optional?
  • positional (like copy <first> <last>) or named (like csc /t:library)?
  • what’s the type of the argument?
  • how to validate an argument’s value?
  • support for “parameter set”?
  • etc

… But if you find yourself in a scenario where it just feels right to write a .NET console application or to add command-line support to any kind of application, System.Shell.CommandLine should be your next big friend…

…”

OMG, finally!

Let’s see I’ve written about one zillion command line parsing code blocks/libraries/modules/things (well actually 5’ish and then upgraded/converted/reused them a zillion times). Stuff like this, done right, is a perfect addition to .Net.

Update #1 3/8/2009 @ 1:12pm PDT:
Looks like this was a mistake, something that was in the CTP that shouldn't have been. Command Line Parsing in .Net 4.0? – Um… Whoops!

Keep an eye out for a CodePlex'ed Command Line API coming from Microsoft...

3 comments:

Anonymous said...

It seems that it might not be as perfect as it should be....

System.Shell.CommandLine does not belong in System.Core

Anonymous said...

See http://tirania.org/blog/archive/2009/Feb-21.html

Greg said...

@Anonymous

FYI, that's same link that Jos posted yesterday... :|