Most of our examples so far have already dealt with options taking arguments, because most options in the real world do take arguments. Today we’ll start looking at option arguments in depth.
The option pipeline post laid out the steps taken when using an Option Arguments class:
- The Option Arguments class is default-constructed.
- Attributes of properties on the class are used to produce a collection of option definitions.
- The command line is parsed, setting properties on the Option Arguments instance.
We’ll take advantage of these steps to handle several common scenarios.
Default argument values are set in the default constructor:
> CommandLineParsingTest.exe Level: 0 Quality: 3 > CommandLineParsingTest.exe /level 7 Level: 7 Quality: 3 > CommandLineParsingTest.exe /quality 4 Level: 0 Quality: 4
There are some situations where a “default value” doesn’t make sense for an option; you need to know whether there was a value passed, and what the value is (if it was passed). In this situation, you can use a nullable value type for your property:
> CommandLineParsingTest.exe Level not specified. Name not specified. > CommandLineParsingTest.exe /level 3 Level: 3 Name not specified. > CommandLineParsingTest.exe /level 0 Level: 0 Name not specified. > CommandLineParsingTest.exe /name Bob Level not specified. Name: Bob > CommandLineParsingTest.exe /name "" Level not specified. Name: