Documentation for the C# command-line option parser

Project Home

The source for this library is hosted at SourceForge .

The project home page and this documentation can be accessed at http://csharpoptparse.sourceforge.net and the project summary page is located at http://sourceforge.net/projects/csharpoptparse.

Back to the top

Support and Licensing

The source code for this project is free protected under the GPL. If you find this code useful and you wish to support this project, please go here: Support This Project

Back to the top

Overview

Although there are a few command-line option parsers available for different languages including .NET, many were not flexible and robust. This library ports a large portion of the functionality from the Perl GetOpt library. In addition to this functionality, additional features have been added that integrate with the .NET language better.

The library revolves around the Parser class. This class uses an implementation of an IOptionResults interface to store results of parsing the command-line. The definition of the options can be done in two ways:

  1. Definition of a class to house options.
  2. Using instances of the OptionDefinition class.

Option class

The parser is able to reflect options from a class that uses attributes (The class does not need to implement or extend anything for this functionality). The attribute classes that can be used are:
Class | Description
OptDefAttribute | Define that a property or field can be given as an option
LongOptionNameAttribute | Defines a long option for a field or property
ShortOptionNameAttribute | Defines a short option name for a field or property
UseNameAsLongOptionAttribute | Gives the ability to stop the name of a field or property being used to be used as an option name

OptionDefinition class

The OptionDefinition class provides a way to programmatically define options at run-time. There are several overloads to the constructor that accept either arguments to define the settings or using the string constructor that parses a Perl-like option definition. Using this method, the results are stored in a dictionary (see OptionResultsDictionary for a strongly-typed dictionary). The attributes are not used in this method.

Back to the top


CommandLine.ConsoleUtils

Documentation for the C# command-line option parsing library

CommandLine.ConsoleUtils Namespace

Contains classes used to help interact with the .NET command console

Namespace hierarchy

Classes

Class | Description
ConsoleHelper | Class to help with more advanced console functions

Structures

Structure | Description
ConsolePoint | Position in the console
ConsoleRect | Rectangle in the console
ConsoleScreenBufferInfo | Information on the current screen buffer

Send comments on this topic.

Copyright 2005, Andrew Robinson


ConsoleHelper Class

Class to help with more advanced console functions

For a list of all members of this type, see ConsoleHelper Members.

System.Object
CommandLine.ConsoleUtils.ConsoleHelper

public class ConsoleHelper

Requirements

Namespace: CommandLine.ConsoleUtils

Assembly: CSharpOptParse (in CSharpOptParse.dll)

See Also

ConsoleHelper Members | CommandLine.ConsoleUtils Namespace


ConsoleHelper Members

ConsoleHelper overview

Public Instance Constructors

ConsoleHelper Constructor Cosntructor

Public Instance Methods

Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetCursorPos | Get the cursor position
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetScreenInfo | Get the current screen information
GetType (inherited from Object) | Gets the Type of the current instance.
SetCursorPos | Set the cursor position
ToString (inherited from Object) | Returns a String that represents the current Object.

Protected Instance Methods

Finalize (inherited from Object) | Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection.
MemberwiseClone (inherited from Object) | Creates a shallow copy of the current Object.

See Also

ConsoleHelper Class | CommandLine.ConsoleUtils Namespace


ConsoleHelper Constructor

Cosntructor

public ConsoleHelper();

See Also

ConsoleHelper Class | CommandLine.ConsoleUtils Namespace


ConsoleHelper Methods

The methods of the ConsoleHelper class are listed below. For a complete list of ConsoleHelper class members, see the ConsoleHelper Members topic.

Public Instance Methods

Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetCursorPos | Get the cursor position
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetScreenInfo | Get the current screen information
GetType (inherited from Object) | Gets the Type of the current instance.
SetCursorPos | Set the cursor position
ToString (inherited from Object) | Returns a String that represents the current Object.

Protected Instance Methods

Finalize (inherited from Object) | Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection.
MemberwiseClone (inherited from Object) | Creates a shallow copy of the current Object.

See Also

ConsoleHelper Class | CommandLine.ConsoleUtils Namespace


ConsoleHelper.GetCursorPos Method

Get the cursor position

public ConsolePoint GetCursorPos();

See Also

ConsoleHelper Class | CommandLine.ConsoleUtils Namespace


ConsoleHelper.GetScreenInfo Method

Get the current screen information

public ConsoleScreenBufferInfo GetScreenInfo();

See Also

ConsoleHelper Class | CommandLine.ConsoleUtils Namespace


ConsoleHelper.SetCursorPos Method

Set the cursor position

public void SetCursorPos(
short x,
short y
);

See Also

ConsoleHelper Class | CommandLine.ConsoleUtils Namespace


ConsolePoint Structure

Position in the console

For a list of all members of this type, see ConsolePoint Members.

System.Object
System.ValueType
CommandLine.ConsoleUtils.ConsolePoint

[StructLayout(Value=Sequential)]
public struct ConsolePoint

Requirements

Namespace: CommandLine.ConsoleUtils

Assembly: CSharpOptParse (in CSharpOptParse.dll)

See Also

ConsolePoint Members | CommandLine.ConsoleUtils Namespace


ConsolePoint Members

ConsolePoint overview

Public Instance Constructors

ConsolePoint Constructor Constructor

Public Instance Fields

X | X coordinate
Y | Y coordinate

Public Instance Methods

Equals (inherited from ValueType) | Indicates whether this instance and a specified object are equal.
GetHashCode (inherited from ValueType) | Returns the hash code for this instance.
GetType (inherited from Object) | Gets the Type of the current instance.
ToString (inherited from ValueType) | Returns the fully qualified type name of this instance.

See Also

ConsolePoint Class | CommandLine.ConsoleUtils Namespace


ConsolePoint Constructor

Constructor

public ConsolePoint(
short x,
short y
);

See Also

ConsolePoint Class | CommandLine.ConsoleUtils Namespace


ConsolePoint Fields

The fields of the ConsolePoint structure are listed below. For a complete list of ConsolePoint structure members, see the ConsolePoint Members topic.

Public Instance Fields

X | X coordinate
Y | Y coordinate

See Also

ConsolePoint Class | CommandLine.ConsoleUtils Namespace


ConsolePoint.X Field

X coordinate

public short X;

See Also

ConsolePoint Class | CommandLine.ConsoleUtils Namespace


ConsolePoint.Y Field

Y coordinate

public short Y;

See Also

ConsolePoint Class | CommandLine.ConsoleUtils Namespace


ConsoleRect Structure

Rectangle in the console

For a list of all members of this type, see ConsoleRect Members.

System.Object
System.ValueType
CommandLine.ConsoleUtils.ConsoleRect

[StructLayout(Value=Sequential)]
public struct ConsoleRect

Requirements

Namespace: CommandLine.ConsoleUtils

Assembly: CSharpOptParse (in CSharpOptParse.dll)

See Also

ConsoleRect Members | CommandLine.ConsoleUtils Namespace


ConsoleRect Members

ConsoleRect overview

Public Instance Fields

Bottom | Bottom edge
Left | Left edge
Right | Right edge
Top | Top edge

Public Instance Methods

Equals (inherited from ValueType) | Indicates whether this instance and a specified object are equal.
GetHashCode (inherited from ValueType) | Returns the hash code for this instance.
GetType (inherited from Object) | Gets the Type of the current instance.
ToString (inherited from ValueType) | Returns the fully qualified type name of this instance.

See Also

ConsoleRect Class | CommandLine.ConsoleUtils Namespace


ConsoleRect Fields

The fields of the ConsoleRect structure are listed below. For a complete list of ConsoleRect structure members, see the ConsoleRect Members topic.

Public Instance Fields

Bottom | Bottom edge
Left | Left edge
Right | Right edge
Top | Top edge

See Also

ConsoleRect Class | CommandLine.ConsoleUtils Namespace


ConsoleRect.Bottom Field

Bottom edge

public short Bottom;

See Also

ConsoleRect Class | CommandLine.ConsoleUtils Namespace


ConsoleRect.Left Field

Left edge

public short Left;

See Also

ConsoleRect Class | CommandLine.ConsoleUtils Namespace


ConsoleRect.Right Field

Right edge

public short Right;

See Also

ConsoleRect Class | CommandLine.ConsoleUtils Namespace


ConsoleRect.Top Field

Top edge

public short Top;

See Also

ConsoleRect Class | CommandLine.ConsoleUtils Namespace


ConsoleScreenBufferInfo Structure

Information on the current screen buffer

For a list of all members of this type, see ConsoleScreenBufferInfo Members.

System.Object
System.ValueType
CommandLine.ConsoleUtils.ConsoleScreenBufferInfo

[StructLayout(Value=Sequential)]
public struct ConsoleScreenBufferInfo

Requirements

Namespace: CommandLine.ConsoleUtils

Assembly: CSharpOptParse (in CSharpOptParse.dll)

See Also

ConsoleScreenBufferInfo Members | CommandLine.ConsoleUtils Namespace


ConsoleScreenBufferInfo Members

ConsoleScreenBufferInfo overview

Public Instance Fields

Attributes | Attributes
CursorPosition | Position of the cursor on the screen
MaximumWindowSize | Maximum window size
Size | Size of the screen buffer
Window | Bounds of the window

Public Instance Methods

Equals (inherited from ValueType) | Indicates whether this instance and a specified object are equal.
GetHashCode (inherited from ValueType) | Returns the hash code for this instance.
GetType (inherited from Object) | Gets the Type of the current instance.
ToString (inherited from ValueType) | Returns the fully qualified type name of this instance.

See Also

ConsoleScreenBufferInfo Class | CommandLine.ConsoleUtils Namespace


ConsoleScreenBufferInfo Fields

The fields of the ConsoleScreenBufferInfo structure are listed below. For a complete list of ConsoleScreenBufferInfo structure members, see the ConsoleScreenBufferInfo Members topic.

Public Instance Fields

Attributes | Attributes
CursorPosition | Position of the cursor on the screen
MaximumWindowSize | Maximum window size
Size | Size of the screen buffer
Window | Bounds of the window

See Also

ConsoleScreenBufferInfo Class | CommandLine.ConsoleUtils Namespace


ConsoleScreenBufferInfo.Attributes Field

Attributes

public int Attributes;

See Also

ConsoleScreenBufferInfo Class | CommandLine.ConsoleUtils Namespace


ConsoleScreenBufferInfo.CursorPosition Field

Position of the cursor on the screen

public ConsolePoint CursorPosition;

See Also

ConsoleScreenBufferInfo Class | CommandLine.ConsoleUtils Namespace


ConsoleScreenBufferInfo.MaximumWindowSize Field

Maximum window size

public ConsolePoint MaximumWindowSize;

See Also

ConsoleScreenBufferInfo Class | CommandLine.ConsoleUtils Namespace


ConsoleScreenBufferInfo.Size Field

Size of the screen buffer

public ConsolePoint Size;

See Also

ConsoleScreenBufferInfo Class | CommandLine.ConsoleUtils Namespace


ConsoleScreenBufferInfo.Window Field

Bounds of the window

public ConsoleRect Window;

See Also

ConsoleScreenBufferInfo Class | CommandLine.ConsoleUtils Namespace


CommandLine.OptParse

Documentation for the C# command-line option parsing library

CommandLine.OptParse Namespace

Contains the functionality for parsing command-line options. The primary classes to focus on are the Parser and UsageBuilder classes.

Namespace hierarchy

Classes

Class | Description
DefaultUsageInfo | Obsolete. A simple, default implementation of IProgUsageInfo that is fairly easy to use
DictionaryParserHelper | Class that parses option results into a dictionary interface
EnumDescriptorReader | Class that assists with reading DescriptionAttribute values for enumeration values
InvalidValueException | Parsing exception that is thrown if a value is given that is not of the expected type
LongOptionNameAttribute | Defines a long option for a field or property
OptDefAttribute | Define that a property or field can be given as an option
OptionDefinition | Definition of an option
OptionResult | Stores the information on the result of parsing an option
OptionResultsDictionary | Dictionary of option results
OptionWarningEventArgs | Event args for parse warnings
ParseException | Exception thrown if the parser encounters an error
Parser | Class that parses the command line options. Use the ParserFactory to construct an instance of a parser
ParserFactory | Factory to build parser instances
PropertyFieldParserHelper | Helper class for the parser that stores values into properties and fields of a class.
ShortOptionNameAttribute | Defines a short option name for a field or property
UsageBuilder | Class to assist the building of program usage information
UseNameAsLongOptionAttribute | Gives the ability to stop the name of a field or property being used to be used as an option name

Interfaces

Interface | Description
IOptionContainer | Interface that describes an object that contains option definitions
IOptionResults | Interface for interacting with the results of parsing the options
IProgUsageInfo | Obsolete. Interface for the parser to use to be able to print usage information for the given program.

Delegates

Delegate | Description
WarningEventHandler | Delegate to receive warning events from a parser

Enumerations

Enumeration | Description
DupOptHandleType | Define the behavior of the parser if an option is duplicated
ListType | Type of list to create in the usage
OptStyle | The platform style of option
OptValType | Type of value that the option permits
UnixShortOption | Specify how short options may be given for Unix-style arguments
UnknownOptHandleType | Define the behavior of the parser if an option is given that is not reconginzed


DefaultUsageInfo Class

NOTE: This class is now obsolete.

Use UsageBuilder instead

A simple, default implementation of IProgUsageInfo that is fairly easy to use

For a list of all members of this type, see DefaultUsageInfo Members.

System.Object
CommandLine.OptParse.DefaultUsageInfo

public class DefaultUsageInfo : IProgUsageInfo

Requirements

Namespace: CommandLine.OptParse

Assembly: CSharpOptParse (in CSharpOptParse.dll)

See Also

DefaultUsageInfo Members | CommandLine.OptParse Namespace


DefaultUsageInfo Members

DefaultUsageInfo overview

Public Instance Constructors

DefaultUsageInfo Overloaded. Initializes a new instance of the DefaultUsageInfo class.

Public Instance Properties

Headers Get the headers for the usage

Public Instance Methods

Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetContents | Get the contents of the given header
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetType (inherited from Object) | Gets the Type of the current instance.
IsOptionHeader | Get if the given header should hold the option description
ToString (inherited from Object) | Returns a String that represents the current Object.

Protected Instance Methods

Finalize (inherited from Object) | Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection.
MemberwiseClone (inherited from Object) | Creates a shallow copy of the current Object.

See Also

DefaultUsageInfo Class | CommandLine.OptParse Namespace


DefaultUsageInfo Constructor

Constructor to make argument description construction easier

Overload List

Constructor

public DefaultUsageInfo(string,string,bool,NameValueCollection);

Constructor to make argument description construction easier

public DefaultUsageInfo(string,string,bool,params string[]);

See Also

DefaultUsageInfo Class | CommandLine.OptParse Namespace


DefaultUsageInfo Constructor (String, String, Boolean, String[])

Constructor to make argument description construction easier

public DefaultUsageInfo(
string programName,
string description,
bool upperCase,
params string[] argumentDescription
);

Parameters

programName
The name of the program (something.exe)
description
Description of the program
upperCase
True to use all-upper case headers, or false for title cased headers
argumentDescription
list of descriptions in the format of { "Argument", "Description" [, "Argument", "Description"] ...}

Remarks

The argumentDescriptions array should be an even length. The event indexes (0, 2, 4, etc.) should be the argument names, and the odd indexes are the descriptions of the names (1, 3, etc. where 1 is the description of 0, 3 of 2, etc.).

Example:

new DefaultUsageInfo("HelloWorld.exe", "Says hello world with the arguments",
"Additional text", "Text to print after saying hello world");

See Also

DefaultUsageInfo Class | CommandLine.OptParse Namespace | DefaultUsageInfo Constructor Overload List


DefaultUsageInfo Constructor (String, String, Boolean, NameValueCollection)

Constructor

public DefaultUsageInfo(
string programName,
string description,
bool upperCase,
NameValueCollection argumentDescription
);

Parameters

programName
The name of the program (something.exe)
description
Description of the program
upperCase
True to use all-upper case headers, or false for title cased headers
argumentDescription
Argument name, argument description pairs to describe the arguments the program takes or null if none

See Also

DefaultUsageInfo Class | CommandLine.OptParse Namespace | DefaultUsageInfo Constructor Overload List


DefaultUsageInfo Properties

The properties of the DefaultUsageInfo class are listed below. For a complete list of DefaultUsageInfo class members, see the DefaultUsageInfo Members topic.

Public Instance Properties

Headers Get the headers for the usage

See Also

DefaultUsageInfo Class | CommandLine.OptParse Namespace


DefaultUsageInfo.Headers Property

Get the headers for the usage

public string[] Headers {get;}

Implements

IProgUsageInfo.Headers

See Also

DefaultUsageInfo Class | CommandLine.OptParse Namespace


DefaultUsageInfo Methods

The methods of the DefaultUsageInfo class are listed below. For a complete list of DefaultUsageInfo class members, see the DefaultUsageInfo Members topic.

Public Instance Methods

Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetContents | Get the contents of the given header
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetType (inherited from Object) | Gets the Type of the current instance.
IsOptionHeader | Get if the given header should hold the option description
ToString (inherited from Object) | Returns a String that represents the current Object.

Protected Instance Methods

Finalize (inherited from Object) | Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection.
MemberwiseClone (inherited from Object) | Creates a shallow copy of the current Object.

See Also

DefaultUsageInfo Class | CommandLine.OptParse Namespace


DefaultUsageInfo.GetContents Method

Get the contents of the given header

public string GetContents(
string header
);

Implements

IProgUsageInfo.GetContents

See Also

DefaultUsageInfo Class | CommandLine.OptParse Namespace


DefaultUsageInfo.IsOptionHeader Method

Get if the given header should hold the option description

public bool IsOptionHeader(
string header
);

Parameters

header
The header

Return Value

True if the options header

Implements

IProgUsageInfo.IsOptionHeader

See Also

DefaultUsageInfo Class | CommandLine.OptParse Namespace


DictionaryParserHelper Class

Class that parses option results into a dictionary interface

For a list of all members of this type, see DictionaryParserHelper Members.

System.Object
CommandLine.OptParse.DictionaryParserHelper

public class DictionaryParserHelper : IOptionResults, IOptionContainer

Remarks

The results are populated as {Key:[OptionDefinition] Value:[OptionResult]} pairs

Requirements

Namespace: CommandLine.OptParse

Assembly: CSharpOptParse (in CSharpOptParse.dll)

See Also

DictionaryParserHelper Members | CommandLine.OptParse Namespace | Parser | ParserFactory


DictionaryParserHelper Members

DictionaryParserHelper overview

Public Instance Constructors

DictionaryParserHelper Constructor Constructor

Public Instance Properties

Item See Item

Public Instance Methods

Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetOptionDefinition | Overloaded. See GetOptionDefinition
GetOptions | See GetOptions
GetType (inherited from Object) | Gets the Type of the current instance.
ToString (inherited from Object) | Returns a String that represents the current Object.

Protected Instance Methods

Finalize (inherited from Object) | Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection.
MemberwiseClone (inherited from Object) | Creates a shallow copy of the current Object.

See Also

DictionaryParserHelper Class | CommandLine.OptParse Namespace | Parser | ParserFactory


DictionaryParserHelper Constructor

Constructor

public DictionaryParserHelper(
OptionDefinition[] optDefs,
IDictionary valuesDictionary
);

Parameters

optDefs
The supported options
valuesDictionary
The dictionary that will be used to store the values of the options

See Also

DictionaryParserHelper Class | CommandLine.OptParse Namespace


DictionaryParserHelper Properties

The properties of the DictionaryParserHelper class are listed below. For a complete list of DictionaryParserHelper class members, see the DictionaryParserHelper Members topic.

Public Instance Properties

Item See Item

See Also

DictionaryParserHelper Class | CommandLine.OptParse Namespace | Parser | ParserFactory


DictionaryParserHelper.Item Property

See Item

public OptionResult this[
CommandLine.OptParse.OptionDefinition def
] {get; set;}

Implements

IOptionResults.Item

See Also

DictionaryParserHelper Class | CommandLine.OptParse Namespace


DictionaryParserHelper Methods

The methods of the DictionaryParserHelper class are listed below. For a complete list of DictionaryParserHelper class members, see the DictionaryParserHelper Members topic.

Public Instance Methods

Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetOptionDefinition | Overloaded. See GetOptionDefinition
GetOptions | See GetOptions
GetType (inherited from Object) | Gets the Type of the current instance.
ToString (inherited from Object) | Returns a String that represents the current Object.

Protected Instance Methods

Finalize (inherited from Object) | Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection.
MemberwiseClone (inherited from Object) | Creates a shallow copy of the current Object.

See Also

DictionaryParserHelper Class | CommandLine.OptParse Namespace | Parser | ParserFactory


GetOptionDefinition Method

Documentation for the C# command-line option parsing library

DictionaryParserHelper.GetOptionDefinition Method

See GetOptionDefinition

Overload List

See GetOptionDefinition

public OptionDefinition GetOptionDefinition(char,bool);

See GetOptionDefinition

public OptionDefinition GetOptionDefinition(string,bool);

See Also

DictionaryParserHelper Class | CommandLine.OptParse Namespace


DictionaryParserHelper.GetOptionDefinition Method (Char, Boolean)

See GetOptionDefinition

public OptionDefinition GetOptionDefinition(
char optionName,
bool caseSensitive
);

Implements

IOptionResults.GetOptionDefinition

See Also

DictionaryParserHelper Class | CommandLine.OptParse Namespace | DictionaryParserHelper.GetOptionDefinition Overload List


DictionaryParserHelper.GetOptionDefinition Method (String, Boolean)

See GetOptionDefinition

public OptionDefinition GetOptionDefinition(
string optionName,
bool caseSensitive
);

Implements

IOptionResults.GetOptionDefinition

See Also

DictionaryParserHelper Class | CommandLine.OptParse Namespace | DictionaryParserHelper.GetOptionDefinition Overload List


DictionaryParserHelper.GetOptions Method

See GetOptions

public OptionDefinition[] GetOptions();

Implements

IOptionContainer.GetOptions

See Also

DictionaryParserHelper Class | CommandLine.OptParse Namespace


DupOptHandleType Enumeration

Define the behavior of the parser if an option is duplicated

public enum DupOptHandleType

Remarks

If the option is not defined as a option that allows multiple values, then this enumeration specifies the action to take when a duplicate option is given at the command-line.

Members

Member Name | Description
Allow | Allow the duplicate declaration, using the last declaration to specify the value
Warning | Allow the duplicate declaration, using the last declaration to specify the value, but send a warning back to the caller of the parser (see the OptionWarning event)
Error | Deny the duplicate declaration, throwing a ParseException

Requirements

Namespace: CommandLine.OptParse

Assembly: CSharpOptParse (in CSharpOptParse.dll)

See Also

CommandLine.OptParse Namespace


EnumDescriptorReader Class

Class that assists with reading DescriptionAttribute values for enumeration values

For a list of all members of this type, see EnumDescriptorReader Members.

System.Object
CommandLine.OptParse.EnumDescriptorReader

public sealed class EnumDescriptorReader

Requirements

Namespace: CommandLine.OptParse

Assembly: CSharpOptParse (in CSharpOptParse.dll)

See Also

EnumDescriptorReader Members | CommandLine.OptParse Namespace


EnumDescriptorReader Members

EnumDescriptorReader overview

Public Static Methods

GetEnumFieldDescription | Get the field description for the enumeration value
GetEnumFieldDescriptions | Gets all of the descriptions for the values in the given enumeration type.

Public Instance Methods

Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetType (inherited from Object) | Gets the Type of the current instance.
ToString (inherited from Object) | Returns a String that represents the current Object.

See Also

EnumDescriptorReader Class | CommandLine.OptParse Namespace


EnumDescriptorReader Methods

The methods of the EnumDescriptorReader class are listed below. For a complete list of EnumDescriptorReader class members, see the EnumDescriptorReader Members topic.

Public Static Methods

GetEnumFieldDescription | Get the field description for the enumeration value
GetEnumFieldDescriptions | Gets all of the descriptions for the values in the given enumeration type.

Public Instance Methods

Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetType (inherited from Object) | Gets the Type of the current instance.
ToString (inherited from Object) | Returns a String that represents the current Object.

See Also

EnumDescriptorReader Class | CommandLine.OptParse Namespace


EnumDescriptorReader.GetEnumFieldDescription Method

Get the field description for the enumeration value

public static string GetEnumFieldDescription(
Enum val
);

Parameters

val
The enumeration value to get the description of

Return Value

The description, or if it has none, the name

Example

Enumeration:

public enum ExampleEnum
{
[EnumDescription("This is the first value")]
FirstValue = 1,
[EnumDescription("This is the second value")]
SecondValue = 2
}
Usage:
string desc = EnumDescriptorReader.GetEnumFieldDescription(ExampleEnum.FirstValue);

See Also

EnumDescriptorReader Class | CommandLine.OptParse Namespace


EnumDescriptorReader.GetEnumFieldDescriptions Method

Gets all of the descriptions for the values in the given enumeration type.

public static string[] GetEnumFieldDescriptions(
Type enumType
);

Parameters

enumType
The enumeration type

Return Value

An array of the descriptions.

Remarks

If a description attribute is not found, the enumeration field name will be returned as the description instead

See Also

EnumDescriptorReader Class | CommandLine.OptParse Namespace


InvalidValueException Class

Parsing exception that is thrown if a value is given that is not of the expected type

For a list of all members of this type, see InvalidValueException Members.

System.Object
System.Exception
System.ApplicationException
CommandLine.OptParse.ParseException
CommandLine.OptParse.InvalidValueException

public class InvalidValueException : ParseException

Requirements

Namespace: CommandLine.OptParse

Assembly: CSharpOptParse (in CSharpOptParse.dll)

See Also

InvalidValueException Members | CommandLine.OptParse Namespace


InvalidValueException Members

InvalidValueException overview

Public Instance Constructors

InvalidValueException Overloaded. Initializes a new instance of the InvalidValueException class.

Public Instance Properties

HelpLink (inherited from Exception) | Gets or sets a link to the help file associated with this exception.
InnerException (inherited from Exception) | Gets the Exception instance that caused the current exception.
Message (inherited from Exception) | Gets a message that describes the current exception.
Source (inherited from Exception) | Gets or sets the name of the application or the object that causes the error.
StackTrace (inherited from Exception) | Gets a string representation of the frames on the call stack at the time the current exception was thrown.
TargetSite (inherited from Exception) | Gets the method that throws the current exception.

Public Instance Methods

Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetBaseException (inherited from Exception) | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetObjectData (inherited from Exception) | When overridden in a derived class, sets the SerializationInfo with information about the exception.
GetType (inherited from Object) | Gets the Type of the current instance.
ToString (inherited from Exception) | Creates and returns a string representation of the current exception.

Protected Instance Constructors

InvalidValueException Overloaded. Initializes a new instance of the InvalidValueException class.

Protected Instance Properties

HResult (inherited from Exception) Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception.

Protected Instance Methods

Finalize (inherited from Object) | Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection.
MemberwiseClone (inherited from Object) | Creates a shallow copy of the current Object.

See Also

InvalidValueException Class | CommandLine.OptParse Namespace


InvalidValueException Constructor

Constructor

Overload List

Constructor

public InvalidValueException(Exception);

Constructor for serialization. See ApplicationException

protected InvalidValueException(SerializationInfo,StreamingContext);

Constructor

public InvalidValueException(string);

Constructor

public InvalidValueException(string,Exception);

See Also

InvalidValueException Class | CommandLine.OptParse Namespace


InvalidValueException Constructor (String)

Constructor

public InvalidValueException(
string errMsg
);

Parameters

errMsg
Description of the error that occurred while parsing

See Also

InvalidValueException Class | CommandLine.OptParse Namespace | InvalidValueException Constructor Overload List


InvalidValueException Constructor (Exception)

Constructor

public InvalidValueException(
Exception rootCause
);

Parameters

rootCause
Exception that was thrown during parsing

See Also

InvalidValueException Class | CommandLine.OptParse Namespace | InvalidValueException Constructor Overload List


InvalidValueException Constructor (String, Exception)

Constructor

public InvalidValueException(
string errMsg,
Exception rootCause
);

Parameters

errMsg
Description of the error that occurred while parsing
rootCause
Exception that was thrown during parsing

See Also

InvalidValueException Class | CommandLine.OptParse Namespace | InvalidValueException Constructor Overload List


InvalidValueException Constructor (SerializationInfo, StreamingContext)

Constructor for serialization. See ApplicationException

protected InvalidValueException(
SerializationInfo info,
StreamingContext ctx
);

See Also

InvalidValueException Class | CommandLine.OptParse Namespace | InvalidValueException Constructor Overload List


IOptionContainer Interface

Interface that describes an object that contains option definitions

For a list of all members of this type, see IOptionContainer Members.

CommandLine.OptParse.IOptionContainer
CommandLine.OptParse.IOptionResults

public interface IOptionContainer

Types that implement IOptionContainer

Type | Description
DictionaryParserHelper | Class that parses option results into a dictionary interface
Parser | Class that parses the command line options. Use the ParserFactory to construct an instance of a parser
PropertyFieldParserHelper | Helper class for the parser that stores values into properties and fields of a class.

Requirements

Namespace: CommandLine.OptParse

Assembly: CSharpOptParse (in CSharpOptParse.dll)

See Also

IOptionContainer Members | CommandLine.OptParse Namespace


IOptionContainer Members

IOptionContainer overview

Public Instance Methods

GetOptions Get all of the options

See Also

IOptionContainer Interface | CommandLine.OptParse Namespace


IOptionContainer Methods

The methods of the IOptionContainer interface are listed below. For a complete list of IOptionContainer interface members, see the IOptionContainer Members topic.

Public Instance Methods

GetOptions Get all of the options

See Also

IOptionContainer Interface | CommandLine.OptParse Namespace


IOptionContainer.GetOptions Method

Get all of the options

OptionDefinition[] GetOptions();

Return Value

Array of option definitions

See Also

IOptionContainer Interface | CommandLine.OptParse Namespace


IOptionResults Interface

Interface for interacting with the results of parsing the options

For a list of all members of this type, see IOptionResults Members.

public interface IOptionResults : IOptionContainer

Types that implement IOptionResults

Type | Description
DictionaryParserHelper | Class that parses option results into a dictionary interface
PropertyFieldParserHelper | Helper class for the parser that stores values into properties and fields of a class.

Remarks

This interface allows for storing option results in different formats. The Parser class uses this interface.

The implementation of this interface should be able to index the option definitions in both a case sensitive and case insensitive format. The parser's settings will determine the case sesitivity that will be used.

Requirements

Namespace: CommandLine.OptParse

Assembly: CSharpOptParse (in CSharpOptParse.dll)

See Also

IOptionResults Members | CommandLine.OptParse Namespace


IOptionResults Members

IOptionResults overview

Public Instance Properties

Item Get or set the result of an option by its definition

Public Instance Methods

GetOptionDefinition Overloaded. Get the ID of the option for the provided name

See Also

IOptionResults Interface | CommandLine.OptParse Namespace


IOptionResults Properties

The properties of the IOptionResults interface are listed below. For a complete list of IOptionResults interface members, see the IOptionResults Members topic.

Public Instance Properties

Item Get or set the result of an option by its definition

See Also

IOptionResults Interface | CommandLine.OptParse Namespace


IOptionResults.Item Property

Get or set the result of an option by its definition

OptionResult this[
CommandLine.OptParse.OptionDefinition def
] {get; set;}

See Also

IOptionResults Interface | CommandLine.OptParse Namespace


IOptionResults Methods

The methods of the IOptionResults interface are listed below. For a complete list of IOptionResults interface members, see the IOptionResults Members topic.

Public Instance Methods

GetOptionDefinition Overloaded. Get the ID of the option for the provided name

See Also

IOptionResults Interface | CommandLine.OptParse Namespace


GetOptionDefinition Method

Documentation for the C# command-line option parsing library

IOptionResults.GetOptionDefinition Method

Get the ID of the option for the provided short name

Overload List

Get the ID of the option for the provided short name

OptionDefinition GetOptionDefinition(char,bool);

Get the ID of the option for the provided name

OptionDefinition GetOptionDefinition(string,bool);

See Also

IOptionResults Interface | CommandLine.OptParse Namespace


IOptionResults.GetOptionDefinition Method (Char, Boolean)

Get the ID of the option for the provided short name

OptionDefinition GetOptionDefinition(
char optionName,
bool caseSensitive
);

Parameters

optionName
The short name of the option to get the ID of
caseSensitive
If the option name's case should be considered

Return Value

The definition of the option or null if there is no option defined for the given name

See Also

IOptionResults Interface | CommandLine.OptParse Namespace | IOptionResults.GetOptionDefinition Overload List


IOptionResults.GetOptionDefinition Method (String, Boolean)

Get the ID of the option for the provided name

OptionDefinition GetOptionDefinition(
string optionName,
bool caseSensitive
);

Parameters

optionName
The long name of the option to get the ID of
caseSensitive
If the option name's case should be considered

Return Value

The definition of the option or null if there is no option defined for the given name

See Also

IOptionResults Interface | CommandLine.OptParse Namespace | IOptionResults.GetOptionDefinition Overload List


IProgUsageInfo Interface

NOTE: This interface is now obsolete.

Use UsageBuilder instead

Interface for the parser to use to be able to print usage information for the given program.

For a list of all members of this type, see IProgUsageInfo Members.

public interface IProgUsageInfo

Types that implement IProgUsageInfo

Type | Description
DefaultUsageInfo | Obsolete. A simple, default implementation of IProgUsageInfo that is fairly easy to use

Remarks

The usage structure is similar to the Perl POD structure, of headers with description blocks. The implementation however is not as robust.

Requirements

Namespace: CommandLine.OptParse

Assembly: CSharpOptParse (in CSharpOptParse.dll)

See Also

IProgUsageInfo Members | CommandLine.OptParse Namespace


IProgUsageInfo Members

IProgUsageInfo overview

Public Instance Properties

Headers Get a list of all the "topic" headers for the usage

Public Instance Methods

GetContents | Get the contents of a non-option header
IsOptionHeader | Check if a given header should contain the usage of the options

See Also

IProgUsageInfo Interface | CommandLine.OptParse Namespace


IProgUsageInfo Properties

The properties of the IProgUsageInfo interface are listed below. For a complete list of IProgUsageInfo interface members, see the IProgUsageInfo Members topic.

Public Instance Properties

Headers Get a list of all the "topic" headers for the usage

See Also

IProgUsageInfo Interface | CommandLine.OptParse Namespace


IProgUsageInfo.Headers Property

Get a list of all the "topic" headers for the usage

string[] Headers {get;}

Remarks

Each header is similar to a header in a Unix man page. The header is a title block for the contents to follow. The usage information is broken up into sections, each started with a header. Typical headers are "Description", "Synopsis", "Options", "Arguments"

See Also

IProgUsageInfo Interface | CommandLine.OptParse Namespace


IProgUsageInfo Methods

The methods of the IProgUsageInfo interface are listed below. For a complete list of IProgUsageInfo interface members, see the IProgUsageInfo Members topic.

Public Instance Methods

GetContents | Get the contents of a non-option header
IsOptionHeader | Check if a given header should contain the usage of the options

See Also

IProgUsageInfo Interface | CommandLine.OptParse Namespace


IProgUsageInfo.GetContents Method

Get the contents of a non-option header

string GetContents(
string header
);

Parameters

header
The header to get the contents for

Return Value

The contents for the header

See Also

IProgUsageInfo Interface | CommandLine.OptParse Namespace


IProgUsageInfo.IsOptionHeader Method

Check if a given header should contain the usage of the options

bool IsOptionHeader(
string header
);

Parameters

header
The header to check

Return Value

True if the contents of this header is the options description

See Also

IProgUsageInfo Interface | CommandLine.OptParse Namespace


ListType Enumeration

Type of list to create in the usage

public enum ListType

Members

Member Name | Description
Ordered | Numbered/ordered list
Unordered | Unordered list

Requirements

Namespace: CommandLine.OptParse

Assembly: CSharpOptParse (in CSharpOptParse.dll)

See Also

CommandLine.OptParse Namespace


LongOptionNameAttribute Class

Defines a long option for a field or property

For a list of all members of this type, see LongOptionNameAttribute Members.

System.Object
System.Attribute
CommandLine.OptParse.LongOptionNameAttribute

public class LongOptionNameAttribute : Attribute

Remarks

This is only applicable if the field or property is marked as an option using OptDefAttribute

Example

Example class implementing options via attributes:

// Example class defining properties
class Properties
{
    #region Enumerations
    internal enum ExamplePropertyEnum
    {
        First,
        Second
    }
    #endregion Enumerations

    #region Members
    private ExamplePropertyEnum _exampleEnumProp;
    #endregion Members

    #region Accessed by code properties
    // Cannot be used by the parser easily, but can be used
    // by code
    public ExamplePropertyEnum ExampleEnumProp
    {
        get { return _exampleEnumProp; }
        set { _exampleEnumProp = value; }
    }
    #endregion Accessed by code properties

    #region Options
    // Cannot be used by the parser easily, but can be used
    // by code
    // The EditorBrowsableAttribute is used to hide this
    // property from code
    [OptDef(OptValType.Flag)]
    [LongOptionName("example-enum-prop")]
    [UseNameAsLongOption(false)]
    [Description("Show how to perform complex type option parsing")]
    [EditorBrowsable(EditorBrowsableState.Never)]
    public string ExampleEnumPropAsString
    {
        get { return _exampleEnumProp.ToString(); }
        set
        {
            switch (value.ToLower())
            {
                case "first": _exampleEnumProp = ExamplePropertyEnum.First; break;
                case "second": _exampleEnumProp = ExamplePropertyEnum.Second; break;
                default:
                    throw new ArgumentException(
                        "Invalid value for the example-enum-prop option");
            }
        }
    }

    // Example of how to reverse flag-option values
    [OptDef(OptValType.Flag)]
    [LongOptionName("no-debug")]
    [UseNameAsLongOption(false)]
    [Description("Disable debug output")]
    [EditorBrowsable(EditorBrowsableState.Never)]
    public bool NoDebug
    {
        get { return !this.Debug; }
        set { this.Debug = !value; }
    }

    [ShortOptionName('b')]
    [OptDef(OptValType.Flag)]
    [LongOptionName("debug")]
    [UseNameAsLongOption(false)]
    [Description("Enable debug output")]
    public bool Debug = false;

    [OptDef(OptValType.ValueReq)]
    [ShortOptionName('d')]
    [LongOptionName("directory")]
    [UseNameAsLongOption(false)]
    [Description("Output directory")]
    [DefaultValue(".")]
    public string Directory = ".";

    [OptDef(OptValType.ValueOpt)]
    [ShortOptionName('f')]
    [LongOptionName("file")]
    [UseNameAsLongOption(false)]
    [Description("Input file")]
    public string File = null;

    [OptDef(OptValType.IncrementalFlag)]
    [ShortOptionName('v')]
    [LongOptionName("verbose")]
    [UseNameAsLongOption(false)]
    [Description("Set level of vebosity for debug printing")]
    public int Verbose = 0;

    [OptDef(OptValType.MultValue, ValueType=typeof(string))]
    [ShortOptionName('s')]
    [LongOptionName("strings")]
    [UseNameAsLongOption(false)]
    [Description("Test option that takes multiple values")]
    public StringCollection Strings = new StringCollection();
    #endregion Options
}

Requirements

Namespace: CommandLine.OptParse

Assembly: CSharpOptParse (in CSharpOptParse.dll)

See Also

LongOptionNameAttribute Members | CommandLine.OptParse Namespace


LongOptionNameAttribute Members

LongOptionNameAttribute overview

Public Instance Constructors

LongOptionNameAttribute Constructor Constructor

Public Instance Properties

Name | Get the name of the option
TypeId (inherited from Attribute) | When implemented in a derived class, gets a unique identifier for this Attribute.

Public Instance Methods

Equals (inherited from Attribute) |
GetHashCode (inherited from Attribute) | Returns the hash code for this instance.
GetType (inherited from Object) | Gets the Type of the current instance.
IsDefaultAttribute (inherited from Attribute) | When overridden in a derived class, returns an indication whether the value of this instance is the default value for the derived class.
Match (inherited from Attribute) | When overridden in a derived class, returns a value indicating whether this instance equals a specified object.
ToString (inherited from Object) | Returns a String that represents the current Object.

Protected Instance Methods

Finalize (inherited from Object) | Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection.
MemberwiseClone (inherited from Object) | Creates a shallow copy of the current Object.

See Also

LongOptionNameAttribute Class | CommandLine.OptParse Namespace


LongOptionNameAttribute Constructor

Constructor

public LongOptionNameAttribute(
string name
);

Parameters

name
Name of the option

See Also

LongOptionNameAttribute Class | CommandLine.OptParse Namespace


LongOptionNameAttribute Properties

The properties of the LongOptionNameAttribute class are listed below. For a complete list of LongOptionNameAttribute class members, see the LongOptionNameAttribute Members topic.

Public Instance Properties

Name | Get the name of the option
TypeId (inherited from Attribute) | When implemented in a derived class, gets a unique identifier for this Attribute.

See Also

LongOptionNameAttribute Class | CommandLine.OptParse Namespace


LongOptionNameAttribute.Name Property

Get the name of the option

public string Name {get;}

See Also

LongOptionNameAttribute Class | CommandLine.OptParse Namespace


OptDefAttribute Class

Define that a property or field can be given as an option

For a list of all members of this type, see OptDefAttribute Members.

System.Object
System.Attribute
CommandLine.OptParse.OptDefAttribute

public class OptDefAttribute : Attribute

Remarks

For Flag the property or field must have be type of bool

For IncrementalFlag the property or field must be a integer

For ValueReq or ValueOpt the property or field must be the type of the ValueType property.

For MultValue the property or field must be an IList of values of the type defined by the ValueType property (IList cannot be null).

Example

Example class implementing options via attributes:

// Example class defining properties
class Properties
{
    #region Enumerations
    internal enum ExamplePropertyEnum
    {
        First,
        Second
    }
    #endregion Enumerations

    #region Members
    private ExamplePropertyEnum _exampleEnumProp;
    #endregion Members

    #region Accessed by code properties
    // Cannot be used by the parser easily, but can be used
    // by code
    public ExamplePropertyEnum ExampleEnumProp
    {
        get { return _exampleEnumProp; }
        set { _exampleEnumProp = value; }
    }
    #endregion Accessed by code properties

    #region Options
    // Cannot be used by the parser easily, but can be used
    // by code
    // The EditorBrowsableAttribute is used to hide this
    // property from code
    [OptDef(OptValType.Flag)]
    [LongOptionName("example-enum-prop")]
    [UseNameAsLongOption(false)]
    [Description("Show how to perform complex type option parsing")]
    [EditorBrowsable(EditorBrowsableState.Never)]
    public string ExampleEnumPropAsString
    {
        get { return _exampleEnumProp.ToString(); }
        set
        {
            switch (value.ToLower())
            {
                case "first": _exampleEnumProp = ExamplePropertyEnum.First; break;
                case "second": _exampleEnumProp = ExamplePropertyEnum.Second; break;
                default:
                    throw new ArgumentException(
                        "Invalid value for the example-enum-prop option");
            }
        }
    }

    // Example of how to reverse flag-option values
    [OptDef(OptValType.Flag)]
    [LongOptionName("no-debug")]
    [UseNameAsLongOption(false)]
    [Description("Disable debug output")]
    [EditorBrowsable(EditorBrowsableState.Never)]
    public bool NoDebug
    {
        get { return !this.Debug; }
        set { this.Debug = !value; }
    }

    [ShortOptionName('b')]
    [OptDef(OptValType.Flag)]
    [LongOptionName("debug")]
    [UseNameAsLongOption(false)]
    [Description("Enable debug output")]
    public bool Debug = false;

    [OptDef(OptValType.ValueReq)]
    [ShortOptionName('d')]
    [LongOptionName("directory")]
    [UseNameAsLongOption(false)]
    [Description("Output directory")]
    [DefaultValue(".")]
    public string Directory = ".";

    [OptDef(OptValType.ValueOpt)]
    [ShortOptionName('f')]
    [LongOptionName("file")]
    [UseNameAsLongOption(false)]
    [Description("Input file")]
    public string File = null;

    [OptDef(OptValType.IncrementalFlag)]
    [ShortOptionName('v')]
    [LongOptionName("verbose")]
    [UseNameAsLongOption(false)]
    [Description("Set level of vebosity for debug printing")]
    public int Verbose = 0;

    [OptDef(OptValType.MultValue, ValueType=typeof(string))]
    [ShortOptionName('s')]
    [LongOptionName("strings")]
    [UseNameAsLongOption(false)]
    [Description("Test option that takes multiple values")]
    public StringCollection Strings = new StringCollection();
    #endregion Options
}

Requirements

Namespace: CommandLine.OptParse

Assembly: CSharpOptParse (in CSharpOptParse.dll)

See Also

OptDefAttribute Members | CommandLine.OptParse Namespace | Parser


OptDefAttribute Members

OptDefAttribute overview

Public Instance Constructors

OptDefAttribute Constructor Constructor

Public Instance Properties

OptionValueType | Get the type of value the option takes
TypeId (inherited from Attribute) | When implemented in a derived class, gets a unique identifier for this Attribute.
ValueType | Get or set the type of value to support

Public Instance Methods

Equals (inherited from Attribute) |
GetHashCode (inherited from Attribute) | Returns the hash code for this instance.
GetType (inherited from Object) | Gets the Type of the current instance.
IsDefaultAttribute (inherited from Attribute) | When overridden in a derived class, returns an indication whether the value of this instance is the default value for the derived class.
Match (inherited from Attribute) | When overridden in a derived class, returns a value indicating whether this instance equals a specified object.
ToString (inherited from Object) | Returns a String that represents the current Object.

Protected Instance Methods

Finalize (inherited from Object) | Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection.
MemberwiseClone (inherited from Object) | Creates a shallow copy of the current Object.

See Also

OptDefAttribute Class | CommandLine.OptParse Namespace | Parser


OptDefAttribute Constructor

Constructor

public OptDefAttribute(
OptValType optionValueType
);

Parameters

optionValueType
The type of value the option takes or null to use the type of the property/field

See Also

OptDefAttribute Class | CommandLine.OptParse Namespace


OptDefAttribute Properties

The properties of the OptDefAttribute class are listed below. For a complete list of OptDefAttribute class members, see the OptDefAttribute Members topic.

Public Instance Properties

OptionValueType | Get the type of value the option takes
TypeId (inherited from Attribute) | When implemented in a derived class, gets a unique identifier for this Attribute.
ValueType | Get or set the type of value to support

See Also

OptDefAttribute Class | CommandLine.OptParse Namespace | Parser


OptDefAttribute.OptionValueType Property

Get the type of value the option takes

public OptValType OptionValueType {get;}

See Also

OptDefAttribute Class | CommandLine.OptParse Namespace


OptDefAttribute.ValueType Property

Get or set the type of value to support

public System.Type ValueType {get; set;}

Remarks

For most properties and fields, this is optional (can be left null), but for IList types of properties that take multiple values, this property needs to be set to know how to convert the command-line values to the type the list expects

See Also

OptDefAttribute Class | CommandLine.OptParse Namespace


OptionDefinition Class

Definition of an option

For a list of all members of this type, see OptionDefinition Members.

System.Object
CommandLine.OptParse.OptionDefinition

public class OptionDefinition

Remarks

Use this class to define possible options for a command-line. This is an alternative to using a class with fields and properties defined as options.

Requirements

Namespace: CommandLine.OptParse

Assembly: CSharpOptParse (in CSharpOptParse.dll)

See Also

OptionDefinition Members | CommandLine.OptParse Namespace


OptionDefinition Members

OptionDefinition overview

Public Static Methods

CreateDefinitions Helper method to create OptionDefinition instances for each string in definitions

Public Instance Constructors

OptionDefinition Overloaded. Initializes a new instance of the OptionDefinition class.

Public Instance Properties

Category | Get or set the category of the option
DefaultValue | Default value of the option
Description | Get the user-friendly description of this option
ID | Get the ID for this option
LongNames | Get the long names for this option
ShortNames | Get the short names for this option
Type | Get the type of value the option takes
ValueType | Get the type of value that the option supports (if values are supported)

Public Instance Methods

ConvertValue | Try to convert a given value to the value that this option supports
Equals | See Equals
GetHashCode | See GetHashCode
GetType (inherited from Object) | Gets the Type of the current instance.
ToString | Produce a string version of this variable

Protected Instance Methods

Finalize (inherited from Object) | Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection.
MemberwiseClone (inherited from Object) | Creates a shallow copy of the current Object.

See Also

OptionDefinition Class | CommandLine.OptParse Namespace


OptionDefinition Constructor

Build an option from a Perl-like string syntax

Overload List

Constructor

public OptionDefinition(object,OptValType,Type,string,char);

Constructor

public OptionDefinition(object,OptValType,Type,string,char[]);

Constructor

public OptionDefinition(object,OptValType,Type,string,char[],string[]);

Constructor

public OptionDefinition(object,OptValType,Type,string,string);

Constructor

public OptionDefinition(object,OptValType,Type,string,string,char[],string[]);

Constructor

public OptionDefinition(object,OptValType,Type,string,string[]);

Build an option from a Perl-like string syntax

public OptionDefinition(string);

See Also

OptionDefinition Class | CommandLine.OptParse Namespace


OptionDefinition Constructor (String)

Build an option from a Perl-like string syntax

public OptionDefinition(
string definition
);

Parameters

definition
The option definition

Remarks

The definition must match the following regular expression syntax: ^[\w|]+([:=+][sifd]?)?$.

Explanation:

Part | Description
[\w|]+ | A series of one or more word or character names separated by pipe ('|') characters. Example: help|h|?. In this example, for Unix-style options, the valid option variations would be: --help, -h or -?
[:=+] | A character to define the type of value expected. This is optional, and if not given, the option will be considered a flag. So a definition of help can be given at the command-line like: Program --help. The ':' and '=' requires the type of value (see below). The '+' can be used in two ways. First, it can mean that a flag can be given multiple times (to be counted for example). This usage: verbose+ can be given like: Program --verbose --verbose --verbose to result in a verbosity of 3. With a type of value (see below), it means that the option can have many values. A value of ':' means the option may take a value, and '=' means that a value is required for this option.
[sifd]? | A character to define the type of data to accept. This is optional if the preceding character is '+' (see above). If given, the values map to the following .NET types: s - String, i - Int32, d - Double and f - Float

Examples:
Flag:
    Example show help: help|h|?
Flag that gets counted:
    Example to set level of verbosity:    verbose|v+
Option with a required string value (Example: set an output directory):
    Example to set an output directory: directory|dir|d=s
Option with an optional integer value:
    Example to count value that defaults to 0: count|c:i
Option that accepts multiple string values:
    Example to specify include patters: include|i+s

See Also

OptionDefinition Class | CommandLine.OptParse Namespace | OptionDefinition Constructor Overload List


OptionDefinition Constructor (Object, OptValType, Type, String, Char)

Constructor

public OptionDefinition(
object ID,
OptValType type,
Type valueType,
string description,
char shortName
);

Parameters

ID
ID of the option
type
Option value type
valueType
the type of value that the option supports (if values are supported, ignored otherwise)
description
User-friendly description of the option
shortName
The short name to map to this option

See Also

OptionDefinition Class | CommandLine.OptParse Namespace | OptionDefinition Constructor Overload List


OptionDefinition Constructor (Object, OptValType, Type, String, Char[])

Constructor

public OptionDefinition(
object ID,
OptValType type,
Type valueType,
string description,
char[] shortNames
);

Parameters

ID
ID of the option
type
Option value type
valueType
the type of value that the option supports (if values are supported, ignored otherwise)
description
User-friendly description of the option
shortNames
The short names to map to this option

See Also

OptionDefinition Class | CommandLine.OptParse Namespace | OptionDefinition Constructor Overload List


OptionDefinition Constructor (Object, OptValType, Type, String, String)

Constructor

public OptionDefinition(
object ID,
OptValType type,
Type valueType,
string description,
string longName
);

Parameters

ID
ID of the option
type
Option value type
valueType
the type of value that the option supports (if values are supported, ignored otherwise)
description
User-friendly description of the option
longName
The long name to map to this option

See Also

OptionDefinition Class | CommandLine.OptParse Namespace | OptionDefinition Constructor Overload List


OptionDefinition Constructor (Object, OptValType, Type, String, String[])

Constructor

public OptionDefinition(
object ID,
OptValType type,
Type valueType,
string description,
string[] longNames
);

Parameters

ID
ID of the option
type
Option value type
valueType
the type of value that the option supports (if values are supported, ignored otherwise)
description
User-friendly description of the option
longNames
The long names to map to this option

See Also

OptionDefinition Class | CommandLine.OptParse Namespace | OptionDefinition Constructor Overload List


OptionDefinition Constructor (Object, OptValType, Type, String, Char[], String[])

Constructor

public OptionDefinition(
object ID,
OptValType type,
Type valueType,
string description,
char[] shortNames,
string[] longNames
);

Parameters

ID
ID of the option
type
Option value type
valueType
the type of value that the option supports (if values are supported, ignored otherwise)
description
User-friendly description of the option
shortNames
The short names to map to this option
longNames
The long names to map to this option

See Also

OptionDefinition Class | CommandLine.OptParse Namespace | OptionDefinition Constructor Overload List


OptionDefinition Constructor (Object, OptValType, Type, String, String, Char[], String[])

Constructor

public OptionDefinition(
object ID,
OptValType type,
Type valueType,
string category,
string description,
char[] shortNames,
string[] longNames
);

Parameters

ID
ID of the option
type
Option value type
valueType
the type of value that the option supports (if values are supported, ignored otherwise)
category
Category to use to group options when printing
description
User-friendly description of the option
shortNames
The short names to map to this option
longNames
The long names to map to this option

See Also

OptionDefinition Class | CommandLine.OptParse Namespace | OptionDefinition Constructor Overload List


OptionDefinition Properties

The properties of the OptionDefinition class are listed below. For a complete list of OptionDefinition class members, see the OptionDefinition Members topic.

Public Instance Properties

Category | Get or set the category of the option
DefaultValue | Default value of the option
Description | Get the user-friendly description of this option
ID | Get the ID for this option
LongNames | Get the long names for this option
ShortNames | Get the short names for this option
Type | Get the type of value the option takes
ValueType | Get the type of value that the option supports (if values are supported)

See Also

OptionDefinition Class | CommandLine.OptParse Namespace


OptionDefinition.Category Property

Get or set the category of the option

public string Category {get; set;}

Remarks

Categories can be used to group the options when the usage is printed using the UsageBuilder

See Also

OptionDefinition Class | CommandLine.OptParse Namespace


OptionDefinition.DefaultValue Property

Default value of the option

public object DefaultValue {get; set;}

See Also

OptionDefinition Class | CommandLine.OptParse Namespace


OptionDefinition.Description Property

Get the user-friendly description of this option

public string Description {get;}

See Also

OptionDefinition Class | CommandLine.OptParse Namespace


OptionDefinition.ID Property

Get the ID for this option

public object ID {get;}

Remarks

Allows an option to be identified if multiple names are used to define this option

See Also

OptionDefinition Class | CommandLine.OptParse Namespace


OptionDefinition.LongNames Property

Get the long names for this option

public string[] LongNames {get;}

Remarks

Null if long names are not supported by this option

See Also

OptionDefinition Class | CommandLine.OptParse Namespace


OptionDefinition.ShortNames Property

Get the short names for this option

public char[] ShortNames {get;}

Remarks

Null if short names are not supported by this option

See Also

OptionDefinition Class | CommandLine.OptParse Namespace


OptionDefinition.Type Property

Get the type of value the option takes

public OptValType Type {get;}

See Also

OptionDefinition Class | CommandLine.OptParse Namespace


OptionDefinition.ValueType Property

Get the type of value that the option supports (if values are supported)

public System.Type ValueType {get;}

See Also

OptionDefinition Class | CommandLine.OptParse Namespace


OptionDefinition Methods

The methods of the OptionDefinition class are listed below. For a complete list of OptionDefinition class members, see the OptionDefinition Members topic.

Public Static Methods

CreateDefinitions Helper method to create OptionDefinition instances for each string in definitions

Public Instance Methods

ConvertValue | Try to convert a given value to the value that this option supports
Equals | See Equals
GetHashCode | See GetHashCode
GetType (inherited from Object) | Gets the Type of the current instance.
ToString | Produce a string version of this variable

Protected Instance Methods

Finalize (inherited from Object) | Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection.
MemberwiseClone (inherited from Object) | Creates a shallow copy of the current Object.

See Also

OptionDefinition Class | CommandLine.OptParse Namespace


OptionDefinition.ConvertValue Method

Try to convert a given value to the value that this option supports

public object ConvertValue(
string value
);

Parameters

value
The value given

Return Value

The converted value or null if the value could not be converted

Exceptions

Exception Type | Condition
InvalidValueException | Thrown if the value could not be converted

See Also

OptionDefinition Class | CommandLine.OptParse Namespace


OptionDefinition.CreateDefinitions Method

Helper method to create OptionDefinition instances for each string in definitions

public static OptionDefinition[] CreateDefinitions(
string[] definitions
);

Parameters

definitions
Definitions (See OptionDefinition)

Return Value

OptionDefinition instances

See Also

OptionDefinition Class | CommandLine.OptParse Namespace


OptionDefinition.Equals Method

See Equals

public override bool Equals(
object obj
);

See Also

OptionDefinition Class | CommandLine.OptParse Namespace


OptionDefinition.GetHashCode Method

See GetHashCode

public override int GetHashCode();

See Also

OptionDefinition Class | CommandLine.OptParse Namespace


OptionDefinition.ToString Method

Produce a string version of this variable

public override string ToString();

See Also

OptionDefinition Class | CommandLine.OptParse Namespace


OptionResult Class

Stores the information on the result of parsing an option

For a list of all members of this type, see OptionResult Members.

System.Object
CommandLine.OptParse.OptionResult

public class OptionResult

Requirements

Namespace: CommandLine.OptParse

Assembly: CSharpOptParse (in CSharpOptParse.dll)

See Also

OptionResult Members | CommandLine.OptParse Namespace | Parser | IOptionResults | OptionResultsDictionary


OptionResult Members

OptionResult overview

Public Instance Constructors

OptionResult Constructor Constructor

Public Instance Properties

Defintion | Get the definition for this result
IsDefined | Get if this property has been defined
NumDefinitions | Get or set the number of times this option was defined
Value | Get or set the value of the option
Values | Get or set all the values given for this option

Public Instance Methods

AddValue | Add a value
Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetType (inherited from Object) | Gets the Type of the current instance.
ToString (inherited from Object) | Returns a String that represents the current Object.

Protected Instance Methods

Finalize (inherited from Object) | Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection.
MemberwiseClone (inherited from Object) | Creates a shallow copy of the current Object.

See Also

OptionResult Class | CommandLine.OptParse Namespace | Parser | IOptionResults | OptionResultsDictionary


OptionResult Constructor

Constructor

public OptionResult(
OptionDefinition def
);

Parameters

def
Definition of the option this result if for

See Also

OptionResult Class | CommandLine.OptParse Namespace


OptionResult Properties

The properties of the OptionResult class are listed below. For a complete list of OptionResult class members, see the OptionResult Members topic.

Public Instance Properties

Defintion | Get the definition for this result
IsDefined | Get if this property has been defined
NumDefinitions | Get or set the number of times this option was defined
Value | Get or set the value of the option
Values | Get or set all the values given for this option

See Also

OptionResult Class | CommandLine.OptParse Namespace | Parser | IOptionResults | OptionResultsDictionary


OptionResult.Defintion Property

Get the definition for this result

public OptionDefinition Defintion {get;}

See Also

OptionResult Class | CommandLine.OptParse Namespace


OptionResult.IsDefined Property

Get if this property has been defined

public bool IsDefined {get;}

See Also

OptionResult Class | CommandLine.OptParse Namespace


OptionResult.NumDefinitions Property

Get or set the number of times this option was defined

public int NumDefinitions {get; set;}

Remarks

If the type of the option supports multiple definitions or multiple values, then this property specifies how many times the option was defined

See Also

OptionResult Class | CommandLine.OptParse Namespace


OptionResult.Value Property

Get or set the value of the option

public object Value {get; set;}

Remarks

This value will always be null for Flag style arguments and may be null for ValueOpt and MultValue options.

If the option is defined multiple times, this will get or set the first value given

See Also

OptionResult Class | CommandLine.OptParse Namespace


OptionResult.Values Property

Get or set all the values given for this option

public System.Collections.ArrayList Values {get;}

Remarks

This property allows access to all the values of the option for use with MultValue type of options

See Also

OptionResult Class | CommandLine.OptParse Namespace | AddValue


OptionResult Methods

The methods of the OptionResult class are listed below. For a complete list of OptionResult class members, see the OptionResult Members topic.

Public Instance Methods

AddValue | Add a value
Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetType (inherited from Object) | Gets the Type of the current instance.
ToString (inherited from Object) | Returns a String that represents the current Object.

Protected Instance Methods

Finalize (inherited from Object) | Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection.
MemberwiseClone (inherited from Object) | Creates a shallow copy of the current Object.

See Also

OptionResult Class | CommandLine.OptParse Namespace | Parser | IOptionResults | OptionResultsDictionary


OptionResult.AddValue Method

Add a value

public void AddValue(
object value
);

Parameters

value
The value to add

Remarks

The value should already be converted to the correct type

See Also

OptionResult Class | CommandLine.OptParse Namespace


OptionResultsDictionary Class

Dictionary of option results

For a list of all members of this type, see OptionResultsDictionary Members.

System.Object
System.Collections.DictionaryBase
CommandLine.OptParse.OptionResultsDictionary

public class OptionResultsDictionary : DictionaryBase

Remarks

When using the DictionaryParserHelper, the helper will use this class to store the results of option parsing in an instance of this class.

Requirements

Namespace: CommandLine.OptParse

Assembly: CSharpOptParse (in CSharpOptParse.dll)

See Also

OptionResultsDictionary Members | CommandLine.OptParse Namespace | DictionaryParserHelper | BuildParser


OptionResultsDictionary Members

OptionResultsDictionary overview

Public Instance Constructors

OptionResultsDictionary Constructor Initializes a new instance of the OptionResultsDictionary class.

Public Instance Properties

Count (inherited from DictionaryBase) | Gets the number of elements contained in the DictionaryBase instance.
Item | Overloaded. Get or set result by definition

Public Instance Methods

Add | Add a result
Clear (inherited from DictionaryBase) | Clears the contents of the DictionaryBase instance.
CopyTo (inherited from DictionaryBase) | Copies the DictionaryBase elements to a one-dimensional Array at the specified index.
Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetEnumerator (inherited from DictionaryBase) | Returns an IDictionaryEnumerator that can iterate through the DictionaryBase instance.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetType (inherited from Object) | Gets the Type of the current instance.
ToString (inherited from Object) | Returns a String that represents the current Object.

Protected Instance Properties

Dictionary (inherited from DictionaryBase) | Gets the list of elements contained in the DictionaryBase instance.
InnerHashtable (inherited from DictionaryBase) | Gets the list of elements contained in the DictionaryBase instance.

Protected Instance Methods

Finalize (inherited from Object) | Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection.
MemberwiseClone (inherited from Object) | Creates a shallow copy of the current Object.
OnClear (inherited from DictionaryBase) | Performs additional custom processes before clearing the contents of the DictionaryBase instance.
OnClearComplete | Update the inner index hashtables
OnGet (inherited from DictionaryBase) | Gets the element with the specified key and value in the DictionaryBase instance.
OnInsert (inherited from DictionaryBase) | Performs additional custom processes before inserting a new element into the DictionaryBase instance.
OnInsertComplete | Update the inner index hashtables
OnRemove (inherited from DictionaryBase) | Performs additional custom processes before removing an element from the DictionaryBase instance.
OnRemoveComplete | Update the inner index hashtables
OnSet (inherited from DictionaryBase) | Performs additional custom processes before setting a value in the DictionaryBase instance.
OnSetComplete | Update the inner index hashtables
OnValidate | Validate the type of the key and value

See Also

OptionResultsDictionary Class | CommandLine.OptParse Namespace | DictionaryParserHelper | BuildParser


OptionResultsDictionary Constructor

Initializes a new instance of the OptionResultsDictionary class.

public OptionResultsDictionary();

See Also

OptionResultsDictionary Class | CommandLine.OptParse Namespace


OptionResultsDictionary Properties

The properties of the OptionResultsDictionary class are listed below. For a complete list of OptionResultsDictionary class members, see the OptionResultsDictionary Members topic.

Public Instance Properties

Count (inherited from DictionaryBase) | Gets the number of elements contained in the DictionaryBase instance.
Item | Overloaded. Get or set result by definition

Protected Instance Properties

Dictionary (inherited from DictionaryBase) | Gets the list of elements contained in the DictionaryBase instance.
InnerHashtable (inherited from DictionaryBase) | Gets the list of elements contained in the DictionaryBase instance.

See Also

OptionResultsDictionary Class | CommandLine.OptParse Namespace | DictionaryParserHelper | BuildParser


Item Property

Documentation for the C# command-line option parsing library

OptionResultsDictionary.Item Property

Get or set result by definition

Overload List

Get or set result by definition

public OptionResult this[CommandLine.OptParse.OptionDefinition] {get; set;}

Get the result by the ID of a definition

public OptionResult this[object] {get;}

See Also

OptionResultsDictionary Class | CommandLine.OptParse Namespace


OptionResultsDictionary.Item Property

Get or set result by definition

public OptionResult this[
CommandLine.OptParse.OptionDefinition key
] {get; set;}

See Also

OptionResultsDictionary Class | CommandLine.OptParse Namespace | OptionResultsDictionary.Item Overload List


OptionResultsDictionary.Item Property

Get the result by the ID of a definition

public OptionResult this[
object ID
] {get;}

See Also

OptionResultsDictionary Class | CommandLine.OptParse Namespace | OptionResultsDictionary.Item Overload List


OptionResultsDictionary Methods

The methods of the OptionResultsDictionary class are listed below. For a complete list of OptionResultsDictionary class members, see the OptionResultsDictionary Members topic.

Public Instance Methods

Add | Add a result
Clear (inherited from DictionaryBase) | Clears the contents of the DictionaryBase instance.
CopyTo (inherited from DictionaryBase) | Copies the DictionaryBase elements to a one-dimensional Array at the specified index.
Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetEnumerator (inherited from DictionaryBase) | Returns an IDictionaryEnumerator that can iterate through the DictionaryBase instance.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetType (inherited from Object) | Gets the Type of the current instance.
ToString (inherited from Object) | Returns a String that represents the current Object.

Protected Instance Methods

Finalize (inherited from Object) | Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection.
MemberwiseClone (inherited from Object) | Creates a shallow copy of the current Object.
OnClear (inherited from DictionaryBase) | Performs additional custom processes before clearing the contents of the DictionaryBase instance.
OnClearComplete | Update the inner index hashtables
OnGet (inherited from DictionaryBase) | Gets the element with the specified key and value in the DictionaryBase instance.
OnInsert (inherited from DictionaryBase) | Performs additional custom processes before inserting a new element into the DictionaryBase instance.
OnInsertComplete | Update the inner index hashtables
OnRemove (inherited from DictionaryBase) | Performs additional custom processes before removing an element from the DictionaryBase instance.
OnRemoveComplete | Update the inner index hashtables
OnSet (inherited from DictionaryBase) | Performs additional custom processes before setting a value in the DictionaryBase instance.
OnSetComplete | Update the inner index hashtables
OnValidate | Validate the type of the key and value

See Also

OptionResultsDictionary Class | CommandLine.OptParse Namespace | DictionaryParserHelper | BuildParser


OptionResultsDictionary.Add Method

Add a result

public void Add(
OptionDefinition key,
OptionResult value
);

Parameters

key
Option definition
value
Result value

See Also

OptionResultsDictionary Class | CommandLine.OptParse Namespace


OptionResultsDictionary.OnClearComplete Method

Update the inner index hashtables

protected override void OnClearComplete();

See Also

OptionResultsDictionary Class | CommandLine.OptParse Namespace


OptionResultsDictionary.OnInsertComplete Method

Update the inner index hashtables

protected override void OnInsertComplete(
object key,
object value
);

See Also

OptionResultsDictionary Class | CommandLine.OptParse Namespace


OptionResultsDictionary.OnRemoveComplete Method

Update the inner index hashtables

protected override void OnRemoveComplete(
object key,
object value
);

See Also

OptionResultsDictionary Class | CommandLine.OptParse Namespace


OptionResultsDictionary.OnSetComplete Method

Update the inner index hashtables

protected override void OnSetComplete(
object key,
object oldValue,
object newValue
);

See Also

OptionResultsDictionary Class | CommandLine.OptParse Namespace


OptionResultsDictionary.OnValidate Method

Validate the type of the key and value

protected override void OnValidate(
object key,
object value
);

See Also

OptionResultsDictionary Class | CommandLine.OptParse Namespace


OptionWarningEventArgs Class

Event args for parse warnings

For a list of all members of this type, see OptionWarningEventArgs Members.

System.Object
System.EventArgs
CommandLine.OptParse.OptionWarningEventArgs

public class OptionWarningEventArgs : EventArgs

Requirements

Namespace: CommandLine.OptParse

Assembly: CSharpOptParse (in CSharpOptParse.dll)

See Also

OptionWarningEventArgs Members | CommandLine.OptParse Namespace


OptionWarningEventArgs Members

OptionWarningEventArgs overview

Public Instance Constructors

OptionWarningEventArgs Constructor Constructor

Public Instance Properties

WarningMessage Get the warning message

Public Instance Methods

Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetType (inherited from Object) | Gets the Type of the current instance.
ToString (inherited from Object) | Returns a String that represents the current Object.

Protected Instance Methods

Finalize (inherited from Object) | Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection.
MemberwiseClone (inherited from Object) | Creates a shallow copy of the current Object.

See Also

OptionWarningEventArgs Class | CommandLine.OptParse Namespace


OptionWarningEventArgs Constructor

Constructor

public OptionWarningEventArgs(
string warningMessage
);

Parameters

warningMessage
The warning message

See Also

OptionWarningEventArgs Class | CommandLine.OptParse Namespace


OptionWarningEventArgs Properties

The properties of the OptionWarningEventArgs class are listed below. For a complete list of OptionWarningEventArgs class members, see the OptionWarningEventArgs Members topic.

Public Instance Properties

WarningMessage Get the warning message

See Also

OptionWarningEventArgs Class | CommandLine.OptParse Namespace


OptionWarningEventArgs.WarningMessage Property

Get the warning message

public string WarningMessage {get;}

See Also

OptionWarningEventArgs Class | CommandLine.OptParse Namespace


OptStyle Enumeration

The platform style of option

public enum OptStyle

Members

Member Name | Description
Windows | Windows style of options (/opt)
Unix | Unix style of options (--opt, -o)

Requirements

Namespace: CommandLine.OptParse

Assembly: CSharpOptParse (in CSharpOptParse.dll)

See Also

CommandLine.OptParse Namespace


OptValType Enumeration

Type of value that the option permits

public enum OptValType

Members

Member Name | Description
Flag | The option does not accept a value
IncrementalFlag | The option does not accept a value, but may be declared multiple times
ValueReq | The option requires a value. If a value is not supplied, an error will be thrown
ValueOpt | The option optional takes a value
MultValue | The option allows 0 to many values

Requirements

Namespace: CommandLine.OptParse

Assembly: CSharpOptParse (in CSharpOptParse.dll)

See Also

CommandLine.OptParse Namespace


ParseException Class

Exception thrown if the parser encounters an error

For a list of all members of this type, see ParseException Members.

System.Object
System.Exception
System.ApplicationException
CommandLine.OptParse.ParseException
CommandLine.OptParse.InvalidValueException

public class ParseException : ApplicationException

Requirements

Namespace: CommandLine.OptParse

Assembly: CSharpOptParse (in CSharpOptParse.dll)

See Also

ParseException Members | CommandLine.OptParse Namespace


ParseException Members

ParseException overview

Public Instance Constructors

ParseException Overloaded. Initializes a new instance of the ParseException class.

Public Instance Properties

HelpLink (inherited from Exception) | Gets or sets a link to the help file associated with this exception.
InnerException (inherited from Exception) | Gets the Exception instance that caused the current exception.
Message (inherited from Exception) | Gets a message that describes the current exception.
Source (inherited from Exception) | Gets or sets the name of the application or the object that causes the error.
StackTrace (inherited from Exception) | Gets a string representation of the frames on the call stack at the time the current exception was thrown.
TargetSite (inherited from Exception) | Gets the method that throws the current exception.

Public Instance Methods

Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetBaseException (inherited from Exception) | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetObjectData (inherited from Exception) | When overridden in a derived class, sets the SerializationInfo with information about the exception.
GetType (inherited from Object) | Gets the Type of the current instance.
ToString (inherited from Exception) | Creates and returns a string representation of the current exception.

Protected Instance Constructors

ParseException Overloaded. Initializes a new instance of the ParseException class.

Protected Instance Properties

HResult (inherited from Exception) Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception.

Protected Instance Methods

Finalize (inherited from Object) | Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection.
MemberwiseClone (inherited from Object) | Creates a shallow copy of the current Object.

See Also

ParseException Class | CommandLine.OptParse Namespace


ParseException Constructor

Constructor

Overload List

Constructor

public ParseException(Exception);

Constructor for serialization. See ApplicationException

protected ParseException(SerializationInfo,StreamingContext);

Constructor

public ParseException(string);

Constructor

public ParseException(string,Exception);

See Also

ParseException Class | CommandLine.OptParse Namespace


ParseException Constructor (String)

Constructor

public ParseException(
string errMsg
);

Parameters

errMsg
Description of the error that occurred while parsing

See Also

ParseException Class | CommandLine.OptParse Namespace | ParseException Constructor Overload List


ParseException Constructor (Exception)

Constructor

public ParseException(
Exception rootCause
);

Parameters

rootCause
Exception that was thrown during parsing

See Also

ParseException Class | CommandLine.OptParse Namespace | ParseException Constructor Overload List


ParseException Constructor (String, Exception)

Constructor

public ParseException(
string errMsg,
Exception rootCause
);

Parameters

errMsg
Description of the error that occurred while parsing
rootCause
Exception that was thrown during parsing

See Also

ParseException Class | CommandLine.OptParse Namespace | ParseException Constructor Overload List


ParseException Constructor (SerializationInfo, StreamingContext)

Constructor for serialization. See ApplicationException

protected ParseException(
SerializationInfo info,
StreamingContext ctx
);

See Also

ParseException Class | CommandLine.OptParse Namespace | ParseException Constructor Overload List


Parser Class

Class that parses the command line options. Use the ParserFactory to construct an instance of a parser

For a list of all members of this type, see Parser Members.

System.Object
CommandLine.OptParse.Parser

public class Parser : IOptionContainer

Remarks

Class that

Example

Example class implementing options via attributes:

// Example class defining properties
class Properties
{
    #region Enumerations
    internal enum ExamplePropertyEnum
    {
        First,
        Second
    }
    #endregion Enumerations

    #region Members
    private ExamplePropertyEnum _exampleEnumProp;
    #endregion Members

    #region Accessed by code properties
    // Cannot be used by the parser easily, but can be used
    // by code
    public ExamplePropertyEnum ExampleEnumProp
    {
        get { return _exampleEnumProp; }
        set { _exampleEnumProp = value; }
    }
    #endregion Accessed by code properties

    #region Options
    // Cannot be used by the parser easily, but can be used
    // by code
    // The EditorBrowsableAttribute is used to hide this
    // property from code
    [OptDef(OptValType.Flag)]
    [LongOptionName("example-enum-prop")]
    [UseNameAsLongOption(false)]
    [Description("Show how to perform complex type option parsing")]
    [EditorBrowsable(EditorBrowsableState.Never)]
    public string ExampleEnumPropAsString
    {
        get { return _exampleEnumProp.ToString(); }
        set
        {
            switch (value.ToLower())
            {
                case "first": _exampleEnumProp = ExamplePropertyEnum.First; break;
                case "second": _exampleEnumProp = ExamplePropertyEnum.Second; break;
                default:
                    throw new ArgumentException(
                        "Invalid value for the example-enum-prop option");
            }
        }
    }

    // Example of how to reverse flag-option values
    [OptDef(OptValType.Flag)]
    [LongOptionName("no-debug")]
    [UseNameAsLongOption(false)]
    [Description("Disable debug output")]
    [EditorBrowsable(EditorBrowsableState.Never)]
    public bool NoDebug
    {
        get { return !this.Debug; }
        set { this.Debug = !value; }
    }

    [ShortOptionName('b')]
    [OptDef(OptValType.Flag)]
    [LongOptionName("debug")]
    [UseNameAsLongOption(false)]
    [Description("Enable debug output")]
    public bool Debug = false;

    [OptDef(OptValType.ValueReq)]
    [ShortOptionName('d')]
    [LongOptionName("directory")]
    [UseNameAsLongOption(false)]
    [Description("Output directory")]
    [DefaultValue(".")]
    public string Directory = ".";

    [OptDef(OptValType.ValueOpt)]
    [ShortOptionName('f')]
    [LongOptionName("file")]
    [UseNameAsLongOption(false)]
    [Description("Input file")]
    public string File = null;

    [OptDef(OptValType.IncrementalFlag)]
    [ShortOptionName('v')]
    [LongOptionName("verbose")]
    [UseNameAsLongOption(false)]
    [Description("Set level of vebosity for debug printing")]
    public int Verbose = 0;

    [OptDef(OptValType.MultValue, ValueType=typeof(string))]
    [ShortOptionName('s')]
    [LongOptionName("strings")]
    [UseNameAsLongOption(false)]
    [Description("Test option that takes multiple values")]
    public StringCollection Strings = new StringCollection();
    #endregion Options
}

Requirements

Namespace: CommandLine.OptParse

Assembly: CSharpOptParse (in CSharpOptParse.dll)

See Also

Parser Members | CommandLine.OptParse Namespace | UsageBuilder | PropertyFieldParserHelper | DictionaryParserHelper | IOptionResults | ParserFactory


Parser Members

Parser overview

Public Instance Constructors

Parser Constructor Constructor

Public Instance Properties

CaseSensitive | Get or set if the parsing of options should consider the case of the options
DupOptHandleType | Get or set how the parser should handle un-expected duplicate option declarations
OptStyle | Get or set the option style to parse
ResultsHandler | Get the handler for the parser
SearchEnvironment | Get or set to search the environment names for values to the options
UnixShortOption | Get how to handle short unix options (with or without bundling)
UnknownOptHandleType | Get or set how to handle unknown options

Public Instance Methods

Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetOptionDefinitions | Get all of the option definitions that have been declared
GetOptionDescriptions | Obsolete. Get a collection of option value, option description pairs
GetOptions | Get the options defined for this parser
GetType (inherited from Object) | Gets the Type of the current instance.
Parse | Overloaded. Parse the GetCommandLineArgs for options using the parser settings
PrintUsage | Overloaded. Prints out the usage of this program to the given text writer
ToString (inherited from Object) | Returns a String that represents the current Object.

Public Instance Events

OptionWarning Event fired when a warning event occurs

Protected Instance Methods

Finalize (inherited from Object) | Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection.
MemberwiseClone (inherited from Object) | Creates a shallow copy of the current Object.

See Also

Parser Class | CommandLine.OptParse Namespace | UsageBuilder | PropertyFieldParserHelper | DictionaryParserHelper | IOptionResults | ParserFactory


Parser Constructor

Constructor

public Parser(
IOptionResults resultsHandler
);

Parameters

resultsHandler
The interface containing the option definitions and handles the results of parsing.

Remarks

The resultsHandler object is resposible for maintaining the option definitions and stores the results of parsing.

The ParserFactory class can assist with constructing instances of the parser (handles IOptionResults object creating). If the factory is not used, the PropertyFieldParserHelper and DictionaryParserHelper classes can be used.

See Also

Parser Class | CommandLine.OptParse Namespace | ParserFactory


Parser Properties

The properties of the Parser class are listed below. For a complete list of Parser class members, see the Parser Members topic.

Public Instance Properties

CaseSensitive | Get or set if the parsing of options should consider the case of the options
DupOptHandleType | Get or set how the parser should handle un-expected duplicate option declarations
OptStyle | Get or set the option style to parse
ResultsHandler | Get the handler for the parser
SearchEnvironment | Get or set to search the environment names for values to the options
UnixShortOption | Get how to handle short unix options (with or without bundling)
UnknownOptHandleType | Get or set how to handle unknown options

See Also

Parser Class | CommandLine.OptParse Namespace | UsageBuilder | PropertyFieldParserHelper | DictionaryParserHelper | IOptionResults | ParserFactory


Parser.CaseSensitive Property

Get or set if the parsing of options should consider the case of the options

[DefaultValue(Value=True)]
public bool CaseSensitive {get; set;}

See Also

Parser Class | CommandLine.OptParse Namespace


Parser.DupOptHandleType Property

Get or set how the parser should handle un-expected duplicate option declarations

[DefaultValue(Value=DupOptHandleType.Warning)]
public DupOptHandleType DupOptHandleType {get; set;}

See Also

Parser Class | CommandLine.OptParse Namespace


Parser.OptStyle Property

Get or set the option style to parse

public OptStyle OptStyle {get; set;}

See Also

Parser Class | CommandLine.OptParse Namespace


Parser.ResultsHandler Property

Get the handler for the parser

public IOptionResults ResultsHandler {get;}

See Also

Parser Class | CommandLine.OptParse Namespace


Parser.SearchEnvironment Property

Get or set to search the environment names for values to the options

[DefaultValue(Value=False)]
public bool SearchEnvironment {get; set;}

Remarks

If set to true, environment variable values will be used if found and the options are not given on the command line. The prefixes (--, -, or /) are not used, only the names of the options when searching the environment.

See Also

Parser Class | CommandLine.OptParse Namespace


Parser.UnixShortOption Property

Get how to handle short unix options (with or without bundling)

[DefaultValue(Value=UnixShortOption.ShortSeparated)]
public UnixShortOption UnixShortOption {get; set;}

See Also

Parser Class | CommandLine.OptParse Namespace


Parser.UnknownOptHandleType Property

Get or set how to handle unknown options

[DefaultValue(Value=UnknownOptHandleType.Warning)]
public UnknownOptHandleType UnknownOptHandleType {get; set;}

See Also

Parser Class | CommandLine.OptParse Namespace


Parser Methods

The methods of the Parser class are listed below. For a complete list of Parser class members, see the Parser Members topic.

Public Instance Methods

Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetOptionDefinitions | Get all of the option definitions that have been declared
GetOptionDescriptions | Obsolete. Get a collection of option value, option description pairs
GetOptions | Get the options defined for this parser
GetType (inherited from Object) | Gets the Type of the current instance.
Parse | Overloaded. Parse the GetCommandLineArgs for options using the parser settings
PrintUsage | Overloaded. Prints out the usage of this program to the given text writer
ToString (inherited from Object) | Returns a String that represents the current Object.

Protected Instance Methods

Finalize (inherited from Object) | Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection.
MemberwiseClone (inherited from Object) | Creates a shallow copy of the current Object.

See Also

Parser Class | CommandLine.OptParse Namespace | UsageBuilder | PropertyFieldParserHelper | DictionaryParserHelper | IOptionResults | ParserFactory


Parser.GetOptionDefinitions Method

Get all of the option definitions that have been declared

public OptionDefinition[] GetOptionDefinitions();

Return Value

Array of option definitions

See Also

Parser Class | CommandLine.OptParse Namespace


Parser.GetOptionDescriptions Method

NOTE: This method is now obsolete.

Use UsageBuilder instead

Get a collection of option value, option description pairs

public NameValueCollection GetOptionDescriptions(
OptStyle style
);

Parameters

style
The style of options. During concatination, the appropriate prefix ('/', '-' or '--') will be added to each option name

Return Value

Collection of the options and their descriptions

Remarks

Used to help print the usage of the application. This function concatinates the options together into one string that is used as the key of the collection, and then sets the value as the description of the option.

Example result:

Key  : -h, --help
Value: Print the usage of this application
Here, the key is a comma concatination of the options and the value is the description of that option.

Short names will precede the long options in the key.

See Also

Parser Class | CommandLine.OptParse Namespace


Parser.GetOptions Method

Get the options defined for this parser

public OptionDefinition[] GetOptions();

Return Value

All of the defined options

Implements

IOptionContainer.GetOptions

See Also

Parser Class | CommandLine.OptParse Namespace


Parse Method

Documentation for the C# command-line option parsing library

Parser.Parse Method

Parse the GetCommandLineArgs for options using the parser settings

Overload List

Parse the GetCommandLineArgs for options using the parser settings

public string[] Parse();

Parse the arguments for options using the given settings

public string[] Parse(OptStyle,UnixShortOption,DupOptHandleType,UnknownOptHandleType,bool,string[]);

Parse the arguments for options using the parser settings

public string[] Parse(string[]);

See Also

Parser Class | CommandLine.OptParse Namespace


Parser.Parse Method ()

Parse the GetCommandLineArgs for options using the parser settings

public string[] Parse();

Return Value

Arguments from the command-line that were not options

See Also

Parser Class | CommandLine.OptParse Namespace | Parser.Parse Overload List


Parser.Parse Method (OptStyle, UnixShortOption, DupOptHandleType, UnknownOptHandleType, Boolean, String[])

Parse the arguments for options using the given settings

public string[] Parse(
OptStyle optStyle,
UnixShortOption unixShortOption,
DupOptHandleType dupOptHandleType,
UnknownOptHandleType unknownOptHandleType,
bool caseSesitive,
string[] args
);

Parameters

optStyle
What type of options to parse
unixShortOption
How to parse unix short options (ignored if not unix style parsing)
dupOptHandleType
How to handle un-expected duplicate option definitions
unknownOptHandleType
How to handle options that were not defined
caseSesitive
If the parsing of options should consider the case of the options
args
The command-line arguments to parse

Return Value

Arguments from the command-line that were not options

See Also

Parser Class | CommandLine.OptParse Namespace | Parser.Parse Overload List


Parser.Parse Method (String[])

Parse the arguments for options using the parser settings

public string[] Parse(
string[] args
);

Parameters

args
The command-line arguments to parse

Return Value

Arguments from the command-line that were not options

See Also

Parser Class | CommandLine.OptParse Namespace | Parser.Parse Overload List


PrintUsage Method

Documentation for the C# command-line option parsing library

Parser.PrintUsage Method

NOTE: This method is now obsolete.

Use UsageBuilder instead

Prints out the usage of this program to the given text writer

Overload List

Obsolete. Prints out the usage of this program to the given text writer

public void PrintUsage(OptStyle,IProgUsageInfo,int);

Obsolete. Prints out the usage of this program to the given text writer

public void PrintUsage(OptStyle,IProgUsageInfo,TextWriter,int);

See Also

Parser Class | CommandLine.OptParse Namespace | IProgUsageInfo | DefaultUsageInfo | GetOptionDescriptions


Parser.PrintUsage Method (OptStyle, IProgUsageInfo, Int32)

NOTE: This method is now obsolete.

Use UsageBuilder instead

Prints out the usage of this program to the given text writer

public void PrintUsage(
OptStyle optStyle,
IProgUsageInfo usageInfo,
int columns
);

Parameters

optStyle
The style of the options to have printed in the usage
usageInfo
columns
The number of columns to print before wrapping the text. Used to correctly format the indenting

Remarks

Prints the usage to the standard output. See IProgUsageInfo and GetOptionDescriptions for more information on how the usage is printed.

At this time, wrapping is not done at word boundries

See Also

Parser Class | CommandLine.OptParse Namespace | Parser.PrintUsage Overload List | IProgUsageInfo | DefaultUsageInfo | GetOptionDescriptions


Parser.PrintUsage Method (OptStyle, IProgUsageInfo, TextWriter, Int32)

NOTE: This method is now obsolete.

Use UsageBuilder instead

Prints out the usage of this program to the given text writer

public void PrintUsage(
OptStyle optStyle,
IProgUsageInfo usageInfo,
TextWriter writer,
int columns
);

Parameters

optStyle
The style of the options to have printed in the usage
usageInfo
writer
The writer to print the usage to
columns
The number of columns to print before wrapping the text. Used to correctly format the indenting

Remarks

Prints the usage to the given writer. See IProgUsageInfo and GetOptionDescriptions for more information on how the usage is printed.

At this time, wrapping is not done at word boundries

See Also

Parser Class | CommandLine.OptParse Namespace | Parser.PrintUsage Overload List | IProgUsageInfo | DefaultUsageInfo | GetOptionDescriptions


Parser Events

The events of the Parser class are listed below. For a complete list of Parser class members, see the Parser Members topic.

Public Instance Events

OptionWarning Event fired when a warning event occurs

See Also

Parser Class | CommandLine.OptParse Namespace | UsageBuilder | PropertyFieldParserHelper | DictionaryParserHelper | IOptionResults | ParserFactory


Parser.OptionWarning Event

Event fired when a warning event occurs

public event WarningEventHandler OptionWarning;

Event Data

The event handler receives an argument of type OptionWarningEventArgs containing data related to this event. The following OptionWarningEventArgs property provides information specific to this event.

Property | Description
WarningMessage | Get the warning message

See Also

Parser Class | CommandLine.OptParse Namespace


ParserFactory Class

Factory to build parser instances

For a list of all members of this type, see ParserFactory Members.

System.Object
CommandLine.OptParse.ParserFactory

public sealed class ParserFactory

Requirements

Namespace: CommandLine.OptParse

Assembly: CSharpOptParse (in CSharpOptParse.dll)

See Also

ParserFactory Members | CommandLine.OptParse Namespace | Parser | ParserFactory | UsageBuilder


ParserFactory Members

ParserFactory overview

Public Static Methods

BuildParser Overloaded. Build a parser

Public Instance Methods

Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetType (inherited from Object) | Gets the Type of the current instance.
ToString (inherited from Object) | Returns a String that represents the current Object.

See Also

ParserFactory Class | CommandLine.OptParse Namespace | Parser | ParserFactory | UsageBuilder


ParserFactory Methods

The methods of the ParserFactory class are listed below. For a complete list of ParserFactory class members, see the ParserFactory Members topic.

Public Static Methods

BuildParser Overloaded. Build a parser

Public Instance Methods

Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetType (inherited from Object) | Gets the Type of the current instance.
ToString (inherited from Object) | Returns a String that represents the current Object.

See Also

ParserFactory Class | CommandLine.OptParse Namespace | Parser | ParserFactory | UsageBuilder


BuildParser Method

Documentation for the C# command-line option parsing library

ParserFactory.BuildParser Method

Build a parser using a custom IOptionResults handler.

Overload List

Build a parser using a custom IOptionResults handler.

public static Parser BuildParser(IOptionResults);

Build a parser

public static Parser BuildParser(OptionDefinition[],OptionResultsDictionary);

Build a parser

public static Parser BuildParser(OptionDefinition[],IDictionary);

Build a parser

public static Parser BuildParser(object);

See Also

ParserFactory Class | CommandLine.OptParse Namespace


ParserFactory.BuildParser Method (IOptionResults)

Build a parser using a custom IOptionResults handler.

public static Parser BuildParser(
IOptionResults resultsHandler
);

Parameters

resultsHandler
Custom handler

Return Value

Parser instance

See Also

ParserFactory Class | CommandLine.OptParse Namespace | ParserFactory.BuildParser Overload List


ParserFactory.BuildParser Method (OptionDefinition[], OptionResultsDictionary)

Build a parser

public static Parser BuildParser(
OptionDefinition[] optDefs,
OptionResultsDictionary valuesDictionary
);

Parameters

optDefs
The supported options
valuesDictionary
The dictionary to store the option results in

Return Value

Parser instance

See Also

ParserFactory Class | CommandLine.OptParse Namespace | ParserFactory.BuildParser Overload List


ParserFactory.BuildParser Method (OptionDefinition[], IDictionary)

Build a parser

public static Parser BuildParser(
OptionDefinition[] optDefs,
IDictionary valuesDictionary
);

Parameters

optDefs
The supported options
valuesDictionary
Dictionary to recieve parsed option values

Return Value

Parser instance

See Also

ParserFactory Class | CommandLine.OptParse Namespace | ParserFactory.BuildParser Overload List


ParserFactory.BuildParser Method (Object)

Build a parser

public static Parser BuildParser(
object propertiesObject
);

Parameters

propertiesObject
Object containing fields and properties that represent option definitions

Return Value

Parser instance

See Also

ParserFactory Class | CommandLine.OptParse Namespace | ParserFactory.BuildParser Overload List


PropertyFieldParserHelper Class

Helper class for the parser that stores values into properties and fields of a class.

For a list of all members of this type, see PropertyFieldParserHelper Members.

System.Object
CommandLine.OptParse.PropertyFieldParserHelper

public class PropertyFieldParserHelper : IOptionResults, IOptionContainer

Remarks

Used to create option definitions from properties and fields of an object. Options are defined using OptDefAttribute, UseNameAsLongOptionAttribute, LongOptionNameAttribute, ShortOptionNameAttribute, DefaultValueAttribute, CategoryAttribute, and DescriptionAttribute attributes.

Example

Example class implementing options via attributes:

// Example class defining properties
class Properties
{
    #region Enumerations
    internal enum ExamplePropertyEnum
    {
        First,
        Second
    }
    #endregion Enumerations

    #region Members
    private ExamplePropertyEnum _exampleEnumProp;
    #endregion Members

    #region Accessed by code properties
    // Cannot be used by the parser easily, but can be used
    // by code
    public ExamplePropertyEnum ExampleEnumProp
    {
        get { return _exampleEnumProp; }
        set { _exampleEnumProp = value; }
    }
    #endregion Accessed by code properties

    #region Options
    // Cannot be used by the parser easily, but can be used
    // by code
    // The EditorBrowsableAttribute is used to hide this
    // property from code
    [OptDef(OptValType.Flag)]
    [LongOptionName("example-enum-prop")]
    [UseNameAsLongOption(false)]
    [Description("Show how to perform complex type option parsing")]
    [EditorBrowsable(EditorBrowsableState.Never)]
    public string ExampleEnumPropAsString
    {
        get { return _exampleEnumProp.ToString(); }
        set
        {
            switch (value.ToLower())
            {
                case "first": _exampleEnumProp = ExamplePropertyEnum.First; break;
                case "second": _exampleEnumProp = ExamplePropertyEnum.Second; break;
                default:
                    throw new ArgumentException(
                        "Invalid value for the example-enum-prop option");
            }
        }
    }

    // Example of how to reverse flag-option values
    [OptDef(OptValType.Flag)]
    [LongOptionName("no-debug")]
    [UseNameAsLongOption(false)]
    [Description("Disable debug output")]
    [EditorBrowsable(EditorBrowsableState.Never)]
    public bool NoDebug
    {
        get { return !this.Debug; }
        set { this.Debug = !value; }
    }

    [ShortOptionName('b')]
    [OptDef(OptValType.Flag)]
    [LongOptionName("debug")]
    [UseNameAsLongOption(false)]
    [Description("Enable debug output")]
    public bool Debug = false;

    [OptDef(OptValType.ValueReq)]
    [ShortOptionName('d')]
    [LongOptionName("directory")]
    [UseNameAsLongOption(false)]
    [Description("Output directory")]
    [DefaultValue(".")]
    public string Directory = ".";

    [OptDef(OptValType.ValueOpt)]
    [ShortOptionName('f')]
    [LongOptionName("file")]
    [UseNameAsLongOption(false)]
    [Description("Input file")]
    public string File = null;

    [OptDef(OptValType.IncrementalFlag)]
    [ShortOptionName('v')]
    [LongOptionName("verbose")]
    [UseNameAsLongOption(false)]
    [Description("Set level of vebosity for debug printing")]
    public int Verbose = 0;

    [OptDef(OptValType.MultValue, ValueType=typeof(string))]
    [ShortOptionName('s')]
    [LongOptionName("strings")]
    [UseNameAsLongOption(false)]
    [Description("Test option that takes multiple values")]
    public StringCollection Strings = new StringCollection();
    #endregion Options
}

Requirements

Namespace: CommandLine.OptParse

Assembly: CSharpOptParse (in CSharpOptParse.dll)

See Also

PropertyFieldParserHelper Members | CommandLine.OptParse Namespace | Parser | ParserFactory | OptDefAttribute | UseNameAsLongOptionAttribute | LongOptionNameAttribute | ShortOptionNameAttribute | DefaultValueAttribute | CategoryAttribute | DescriptionAttribute


PropertyFieldParserHelper Members

PropertyFieldParserHelper overview

Public Instance Constructors

PropertyFieldParserHelper Constructor Constructor

Public Instance Properties

Item See Item

Public Instance Methods

Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetOptionDefinition | Overloaded. See GetOptionDefinition
GetOptions | See GetOptions
GetType (inherited from Object) | Gets the Type of the current instance.
ToString (inherited from Object) | Returns a String that represents the current Object.

Protected Instance Methods

Finalize (inherited from Object) | Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection.
MemberwiseClone (inherited from Object) | Creates a shallow copy of the current Object.

See Also

PropertyFieldParserHelper Class | CommandLine.OptParse Namespace | Parser | ParserFactory | OptDefAttribute | UseNameAsLongOptionAttribute | LongOptionNameAttribute | ShortOptionNameAttribute | DefaultValueAttribute | CategoryAttribute | DescriptionAttribute


PropertyFieldParserHelper Constructor

Constructor

public PropertyFieldParserHelper(
object value
);

Parameters

value
The object with the properties and fields defined as options

See Also

PropertyFieldParserHelper Class | CommandLine.OptParse Namespace


PropertyFieldParserHelper Properties

The properties of the PropertyFieldParserHelper class are listed below. For a complete list of PropertyFieldParserHelper class members, see the PropertyFieldParserHelper Members topic.

Public Instance Properties

Item See Item

See Also

PropertyFieldParserHelper Class | CommandLine.OptParse Namespace | Parser | ParserFactory | OptDefAttribute | UseNameAsLongOptionAttribute | LongOptionNameAttribute | ShortOptionNameAttribute | DefaultValueAttribute | CategoryAttribute | DescriptionAttribute


PropertyFieldParserHelper.Item Property

See Item

public OptionResult this[
CommandLine.OptParse.OptionDefinition def
] {get; set;}

Implements

IOptionResults.Item

See Also

PropertyFieldParserHelper Class | CommandLine.OptParse Namespace


PropertyFieldParserHelper Methods

The methods of the PropertyFieldParserHelper class are listed below. For a complete list of PropertyFieldParserHelper class members, see the PropertyFieldParserHelper Members topic.

Public Instance Methods

Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetOptionDefinition | Overloaded. See GetOptionDefinition
GetOptions | See GetOptions
GetType (inherited from Object) | Gets the Type of the current instance.
ToString (inherited from Object) | Returns a String that represents the current Object.

Protected Instance Methods

Finalize (inherited from Object) | Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection.
MemberwiseClone (inherited from Object) | Creates a shallow copy of the current Object.

See Also

PropertyFieldParserHelper Class | CommandLine.OptParse Namespace | Parser | ParserFactory | OptDefAttribute | UseNameAsLongOptionAttribute | LongOptionNameAttribute | ShortOptionNameAttribute | DefaultValueAttribute | CategoryAttribute | DescriptionAttribute


GetOptionDefinition Method

Documentation for the C# command-line option parsing library

PropertyFieldParserHelper.GetOptionDefinition Method

See GetOptionDefinition

Overload List

See GetOptionDefinition

public OptionDefinition GetOptionDefinition(char,bool);

See GetOptionDefinition

public OptionDefinition GetOptionDefinition(string,bool);

See Also

PropertyFieldParserHelper Class | CommandLine.OptParse Namespace


PropertyFieldParserHelper.GetOptionDefinition Method (Char, Boolean)

See GetOptionDefinition

public OptionDefinition GetOptionDefinition(
char optionName,
bool caseSensitive
);

Implements

IOptionResults.GetOptionDefinition

See Also

PropertyFieldParserHelper Class | CommandLine.OptParse Namespace | PropertyFieldParserHelper.GetOptionDefinition Overload List


PropertyFieldParserHelper.GetOptionDefinition Method (String, Boolean)

See GetOptionDefinition

public OptionDefinition GetOptionDefinition(
string optionName,
bool caseSensitive
);

Implements

IOptionResults.GetOptionDefinition

See Also

PropertyFieldParserHelper Class | CommandLine.OptParse Namespace | PropertyFieldParserHelper.GetOptionDefinition Overload List


PropertyFieldParserHelper.GetOptions Method

See GetOptions

public OptionDefinition[] GetOptions();

Implements

IOptionContainer.GetOptions

See Also

PropertyFieldParserHelper Class | CommandLine.OptParse Namespace


ShortOptionNameAttribute Class

Defines a short option name for a field or property

For a list of all members of this type, see ShortOptionNameAttribute Members.

System.Object
System.Attribute
CommandLine.OptParse.ShortOptionNameAttribute

public class ShortOptionNameAttribute : Attribute

Remarks

This is only applicable if the field or property is marked as an option using OptDefAttribute

Example

Example class implementing options via attributes:

// Example class defining properties
class Properties
{
    #region Enumerations
    internal enum ExamplePropertyEnum
    {
        First,
        Second
    }
    #endregion Enumerations

    #region Members
    private ExamplePropertyEnum _exampleEnumProp;
    #endregion Members

    #region Accessed by code properties
    // Cannot be used by the parser easily, but can be used
    // by code
    public ExamplePropertyEnum ExampleEnumProp
    {
        get { return _exampleEnumProp; }
        set { _exampleEnumProp = value; }
    }
    #endregion Accessed by code properties

    #region Options
    // Cannot be used by the parser easily, but can be used
    // by code
    // The EditorBrowsableAttribute is used to hide this
    // property from code
    [OptDef(OptValType.Flag)]
    [LongOptionName("example-enum-prop")]
    [UseNameAsLongOption(false)]
    [Description("Show how to perform complex type option parsing")]
    [EditorBrowsable(EditorBrowsableState.Never)]
    public string ExampleEnumPropAsString
    {
        get { return _exampleEnumProp.ToString(); }
        set
        {
            switch (value.ToLower())
            {
                case "first": _exampleEnumProp = ExamplePropertyEnum.First; break;
                case "second": _exampleEnumProp = ExamplePropertyEnum.Second; break;
                default:
                    throw new ArgumentException(
                        "Invalid value for the example-enum-prop option");
            }
        }
    }

    // Example of how to reverse flag-option values
    [OptDef(OptValType.Flag)]
    [LongOptionName("no-debug")]
    [UseNameAsLongOption(false)]
    [Description("Disable debug output")]
    [EditorBrowsable(EditorBrowsableState.Never)]
    public bool NoDebug
    {
        get { return !this.Debug; }
        set { this.Debug = !value; }
    }

    [ShortOptionName('b')]
    [OptDef(OptValType.Flag)]
    [LongOptionName("debug")]
    [UseNameAsLongOption(false)]
    [Description("Enable debug output")]
    public bool Debug = false;

    [OptDef(OptValType.ValueReq)]
    [ShortOptionName('d')]
    [LongOptionName("directory")]
    [UseNameAsLongOption(false)]
    [Description("Output directory")]
    [DefaultValue(".")]
    public string Directory = ".";

    [OptDef(OptValType.ValueOpt)]
    [ShortOptionName('f')]
    [LongOptionName("file")]
    [UseNameAsLongOption(false)]
    [Description("Input file")]
    public string File = null;

    [OptDef(OptValType.IncrementalFlag)]
    [ShortOptionName('v')]
    [LongOptionName("verbose")]
    [UseNameAsLongOption(false)]
    [Description("Set level of vebosity for debug printing")]
    public int Verbose = 0;

    [OptDef(OptValType.MultValue, ValueType=typeof(string))]
    [ShortOptionName('s')]
    [LongOptionName("strings")]
    [UseNameAsLongOption(false)]
    [Description("Test option that takes multiple values")]
    public StringCollection Strings = new StringCollection();
    #endregion Options
}

Requirements

Namespace: CommandLine.OptParse

Assembly: CSharpOptParse (in CSharpOptParse.dll)

See Also

ShortOptionNameAttribute Members | CommandLine.OptParse Namespace


ShortOptionNameAttribute Members

ShortOptionNameAttribute overview

Public Instance Constructors

ShortOptionNameAttribute Constructor Constructor

Public Instance Properties

Name | Get the name of the option
TypeId (inherited from Attribute) | When implemented in a derived class, gets a unique identifier for this Attribute.

Public Instance Methods

Equals (inherited from Attribute) |
GetHashCode (inherited from Attribute) | Returns the hash code for this instance.
GetType (inherited from Object) | Gets the Type of the current instance.
IsDefaultAttribute (inherited from Attribute) | When overridden in a derived class, returns an indication whether the value of this instance is the default value for the derived class.
Match (inherited from Attribute) | When overridden in a derived class, returns a value indicating whether this instance equals a specified object.
ToString (inherited from Object) | Returns a String that represents the current Object.

Protected Instance Methods

Finalize (inherited from Object) | Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection.
MemberwiseClone (inherited from Object) | Creates a shallow copy of the current Object.

See Also

ShortOptionNameAttribute Class | CommandLine.OptParse Namespace


ShortOptionNameAttribute Constructor

Constructor

public ShortOptionNameAttribute(
char name
);

Parameters

name
Name of the option

See Also

ShortOptionNameAttribute Class | CommandLine.OptParse Namespace


ShortOptionNameAttribute Properties

The properties of the ShortOptionNameAttribute class are listed below. For a complete list of ShortOptionNameAttribute class members, see the ShortOptionNameAttribute Members topic.

Public Instance Properties

Name | Get the name of the option
TypeId (inherited from Attribute) | When implemented in a derived class, gets a unique identifier for this Attribute.

See Also

ShortOptionNameAttribute Class | CommandLine.OptParse Namespace


ShortOptionNameAttribute.Name Property

Get the name of the option

public char Name {get;}

See Also

ShortOptionNameAttribute Class | CommandLine.OptParse Namespace


UnixShortOption Enumeration

Specify how short options may be given for Unix-style arguments

public enum UnixShortOption

Members

Member Name | Description
CollapseShort | Allow short arguments to be collapsed.
ShortSeparated | Short options must be separated, and values do not need a space after the name

Requirements

Namespace: CommandLine.OptParse

Assembly: CSharpOptParse (in CSharpOptParse.dll)

See Also

CommandLine.OptParse Namespace


UnknownOptHandleType Enumeration

Define the behavior of the parser if an option is given that is not reconginzed

public enum UnknownOptHandleType

Members

Member Name | Description
NoAction | Do not do anything, the option will be considered an argument
Warning | A warning will be sent back to the caller of the parser (see the OptionWarning event)
Error | Stop parsing, throwing a ParseException

Requirements

Namespace: CommandLine.OptParse

Assembly: CSharpOptParse (in CSharpOptParse.dll)

See Also

CommandLine.OptParse Namespace


UsageBuilder Class

Class to assist the building of program usage information

For a list of all members of this type, see UsageBuilder Members.

System.Object
CommandLine.OptParse.UsageBuilder

public class UsageBuilder

Remarks

The API of this class is similar to that of an XmlTextWriter. The output of the usage is an XmlDocument. The using the ToHtml, ToText and Transform methods the XML can be transformed into the desired output format for the usage.

Example

Example code printing different usage outputs:

UsageBuilder usage = new UsageBuilder();
usage.GroupOptionsByCategory = false;

usage.BeginSection("Name");
usage.AddParagraph("Tester.exe");
usage.EndSection();

usage.BeginSection("Synopsis");
usage.AddParagraph("Tester.exe [options] [arguments]");
usage.EndSection();

usage.BeginSection("Description");
usage.AddParagraph("Program to test the CSharpOptParse library");

// List of bullets
usage.BeginList(ListType.Unordered);
usage.AddListItem("First");
usage.AddListItem("Second");
usage.EndList();

// Example of creating nested lists:
usage.AddParagraph("Test");
usage.BeginList(ListType.Ordered);
usage.AddListItem("First");
usage.BeginList(ListType.Ordered);
usage.AddListItem("Item");
usage.BeginList(ListType.Ordered);
usage.AddListItem("Item");
usage.BeginList(ListType.Ordered);
usage.AddListItem("Item");
usage.EndList();
usage.EndList();
usage.EndList();
usage.AddListItem("Second");
usage.EndList();

usage.EndSection();

usage.BeginSection("Options");
usage.AddOptions(parser); // parser is an instance of Parser
usage.EndSection();

usage.BeginSection("Arguments");
usage.AddParagraph("Before arguments");
usage.BeginArguments();
usage.AddArgument("Arguments to pass through",
    "Arguments to check if the parsing is returning the correct number of arguments",
    typeof(string), true);
usage.EndArguments();
usage.AddParagraph("After arguments");
usage.EndSection();

using (StreamWriter sw = new StreamWriter("Usage.html"))
{
    usage.ToHtml(sw, OptStyle.Unix, null, true, "Tester.exe");
}

Console.WriteLine("Usage:");
usage.ToText(Console.Out, OptStyle.Unix, true);

Requirements

Namespace: CommandLine.OptParse

Assembly: CSharpOptParse (in CSharpOptParse.dll)

See Also

UsageBuilder Members | CommandLine.OptParse Namespace


UsageBuilder Members

UsageBuilder overview

Public Instance Constructors

UsageBuilder Constructor Default constructor

Public Instance Properties

DefaultOptionCategory | Get or set the category to use for options when an option is missing a category
GroupOptionsByCategory | Get or set to group options by their categories
Usage | Get the XmlDocument containing the usage content

Public Instance Methods

AddArgument | Add an argument overview to the usage
AddListItem | Add a list item tag to the current list
AddOption | Adds an option to the output
AddOptions | Overloaded. Add multiple options to the output
AddParagraph | Add a paragraph to the usage
AddParagraphContent | Add content to the current paragraph node
BeginArgument | Add an argument overview to the usage
BeginArguments | Begin an active "arguments" tag
BeginList | Open a list tag
BeginOption | Method to start adding an option to the usage.
BeginOptions | Begin an active "options" tag
BeginParagraph | Add a paragraph to the usage
BeginSection | Begin a new section tag
EndArgument | Close the active "description" tag and "argument" tags
EndArguments | Close the active "arguments" tag
EndList | Close the active "list" tag
EndOption | Close the active "description" tag and "option" tags
EndOptions | Close the active "options" tag
EndParagraph | Close the active "para" tag
EndSection | Close the section
Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetType (inherited from Object) | Gets the Type of the current instance.
ToHtml | Convert the usage to HTML
ToString (inherited from Object) | Returns a String that represents the current Object.
ToText | Overloaded. Convert the usage to Text
Transform | Convenience method for transforming the XML using a custom XSLT

Protected Instance Methods

Finalize (inherited from Object) | Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection.
MemberwiseClone (inherited from Object) | Creates a shallow copy of the current Object.

See Also

UsageBuilder Class | CommandLine.OptParse Namespace


UsageBuilder Constructor

Default constructor

public UsageBuilder();

See Also

UsageBuilder Class | CommandLine.OptParse Namespace


UsageBuilder Properties

The properties of the UsageBuilder class are listed below. For a complete list of UsageBuilder class members, see the UsageBuilder Members topic.

Public Instance Properties

DefaultOptionCategory | Get or set the category to use for options when an option is missing a category
GroupOptionsByCategory | Get or set to group options by their categories
Usage | Get the XmlDocument containing the usage content

See Also

UsageBuilder Class | CommandLine.OptParse Namespace


UsageBuilder.DefaultOptionCategory Property

Get or set the category to use for options when an option is missing a category

[DefaultValue(Value=Uncategorized)]
public string DefaultOptionCategory {get; set;}

Remarks

Cannot be set to null or an empty string, if so, the default value will be used

See Also

UsageBuilder Class | CommandLine.OptParse Namespace | GroupOptionsByCategory


UsageBuilder.GroupOptionsByCategory Property

Get or set to group options by their categories

public bool GroupOptionsByCategory {get; set;}

See Also

UsageBuilder Class | CommandLine.OptParse Namespace | DefaultOptionCategory


UsageBuilder.Usage Property

Get the XmlDocument containing the usage content

public System.Xml.XmlDocument Usage {get;}

See Also

UsageBuilder Class | CommandLine.OptParse Namespace


UsageBuilder Methods

The methods of the UsageBuilder class are listed below. For a complete list of UsageBuilder class members, see the UsageBuilder Members topic.

Public Instance Methods

AddArgument | Add an argument overview to the usage
AddListItem | Add a list item tag to the current list
AddOption | Adds an option to the output
AddOptions | Overloaded. Add multiple options to the output
AddParagraph | Add a paragraph to the usage
AddParagraphContent | Add content to the current paragraph node
BeginArgument | Add an argument overview to the usage
BeginArguments | Begin an active "arguments" tag
BeginList | Open a list tag
BeginOption | Method to start adding an option to the usage.
BeginOptions | Begin an active "options" tag
BeginParagraph | Add a paragraph to the usage
BeginSection | Begin a new section tag
EndArgument | Close the active "description" tag and "argument" tags
EndArguments | Close the active "arguments" tag
EndList | Close the active "list" tag
EndOption | Close the active "description" tag and "option" tags
EndOptions | Close the active "options" tag
EndParagraph | Close the active "para" tag
EndSection | Close the section
Equals (inherited from Object) | Determines whether the specified Object is equal to the current Object.
GetHashCode (inherited from Object) | Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetType (inherited from Object) | Gets the Type of the current instance.
ToHtml | Convert the usage to HTML
ToString (inherited from Object) | Returns a String that represents the current Object.
ToText | Overloaded. Convert the usage to Text
Transform | Convenience method for transforming the XML using a custom XSLT

Protected Instance Methods

Finalize (inherited from Object) | Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection.
MemberwiseClone (inherited from Object) | Creates a shallow copy of the current Object.

See Also

UsageBuilder Class | CommandLine.OptParse Namespace


UsageBuilder.AddArgument Method

Add an argument overview to the usage

public void AddArgument(
string name,
string description,
Type type,
bool optional
);

Parameters

name
Short name description of the argument
description
Description of the argument
type
Supported data type for the argument (typeof(string) is usually the best choice).
optional
True if the argument should be marked as optional

Remarks

Can only be called when a "section" tag is active. Does not leave a new active tag open.

See Also

UsageBuilder Class | CommandLine.OptParse Namespace


UsageBuilder.AddListItem Method

Add a list item tag to the current list

public void AddListItem(
string body
);

Parameters

body
Body of the list item to add

Remarks

May only be called when a "list" tag is active.

See Also

UsageBuilder Class | CommandLine.OptParse Namespace


UsageBuilder.AddOption Method

Adds an option to the output

public void AddOption(
OptionDefinition opt
);

Parameters

opt
Option to add

Remarks

Like BeginOption, but uses the desription from the option as the body of the "description" tag. Does not open a new active tag

See Also

UsageBuilder Class | CommandLine.OptParse Namespace


AddOptions Method

Documentation for the C# command-line option parsing library

UsageBuilder.AddOptions Method

Add multiple options to the output

Overload List

Add multiple options to the output

public void AddOptions(IOptionContainer);

Add multiple options to the output

public void AddOptions(OptionDefinition[]);

See Also

UsageBuilder Class | CommandLine.OptParse Namespace


UsageBuilder.AddOptions Method (IOptionContainer)

Add multiple options to the output

public void AddOptions(
IOptionContainer optionContainer
);

Parameters

optionContainer
Container with all the options for the program to document

Remarks

Can only be called if the active tag is "section"

See Also

UsageBuilder Class | CommandLine.OptParse Namespace | UsageBuilder.AddOptions Overload List


UsageBuilder.AddOptions Method (OptionDefinition[])

Add multiple options to the output

public void AddOptions(
OptionDefinition[] options
);

Parameters

options
All the options for the program

Remarks

Can only be called if the active tag is "section"

See Also

UsageBuilder Class | CommandLine.OptParse Namespace | UsageBuilder.AddOptions Overload List


UsageBuilder.AddParagraph Method

Add a paragraph to the usage

public void AddParagraph(
string body
);

Parameters

body
The body of the paragraph

Remarks

May only be inside of "section" or "description" tags

See Also

UsageBuilder Class | CommandLine.OptParse Namespace


UsageBuilder.AddParagraphContent Method

Add content to the current paragraph node

public void AddParagraphContent(
string text
);

Parameters

text
Text to add

Remarks

May only be called when a "para" tag is active.

See Also

UsageBuilder Class | CommandLine.OptParse Namespace


UsageBuilder.BeginArgument Method

Add an argument overview to the usage

public void BeginArgument(
string name,
Type type,
bool optional
);

Parameters

name
Short name description of the argument
type
Supported data type for the argument (typeof(string) is usually the best choice).
optional
True if the argument should be marked as optional

Remarks

Can only be called when an "arguments" tag is active. Leaves the "description" tag active under the "argument" tag.

See Also

UsageBuilder Class | CommandLine.OptParse Namespace


UsageBuilder.BeginArguments Method

Begin an active "arguments" tag

public void BeginArguments();

Remarks

May only be called when a "header" tag is active.

See Also

UsageBuilder Class | CommandLine.OptParse Namespace


UsageBuilder.BeginList Method

Open a list tag

public void BeginList(
ListType type
);

Parameters

type
The type of list

Remarks

Sets the active tag to a new "list" tag. May only be called when one of the following tags are active: "section", "paragraph", "list", "description". EndList must be called to close this tag

See Also

UsageBuilder Class | CommandLine.OptParse Namespace


UsageBuilder.BeginOption Method

Method to start adding an option to the usage.

public void BeginOption(
OptionDefinition opt
);

Parameters

opt
Option to start

Remarks

Leaves the "description" tag as the active tag. Allows paragraph and list content to be added to the description of an option beyond the normal description. Does not include the description body from the opt (must be added manually). Call EndOption to close this tag.

See Also

UsageBuilder Class | CommandLine.OptParse Namespace | AddOption


UsageBuilder.BeginOptions Method

Begin an active "options" tag

public void BeginOptions();

Remarks

May only be called when a "header" tag is active.

See Also

UsageBuilder Class | CommandLine.OptParse Namespace | GroupOptionsByCategory | DefaultOptionCategory


UsageBuilder.BeginParagraph Method

Add a paragraph to the usage

public void BeginParagraph();

Remarks

May only be inside of "section" or "description" tags. EndParagraph must be called to close this tag. Use AddParagraphContent to add text to the paragraph body.

See Also

UsageBuilder Class | CommandLine.OptParse Namespace


UsageBuilder.BeginSection Method

Begin a new section tag

public void BeginSection(
string header
);

Parameters

header
Name of the section

Remarks

May only be under a "usage" or "section" tag. EndSection must be called to close this tag

See Also

UsageBuilder Class | CommandLine.OptParse Namespace


UsageBuilder.EndArgument Method

Close the active "description" tag and "argument" tags

public void EndArgument();

Remarks

May only be called when a "description" tag is active below an "argument" tag.

See Also

UsageBuilder Class | CommandLine.OptParse Namespace


UsageBuilder.EndArguments Method

Close the active "arguments" tag

public void EndArguments();

Remarks

May only be called when an "arguments" tag is active.

See Also

UsageBuilder Class | CommandLine.OptParse Namespace


UsageBuilder.EndList Method

Close the active "list" tag

public void EndList();

Remarks

May only be called when a "list" tag is active.

See Also

UsageBuilder Class | CommandLine.OptParse Namespace


UsageBuilder.EndOption Method

Close the active "description" tag and "option" tags

public void EndOption();

Remarks

May only be called when a "description" tag is active below an "option" tag.

See Also

UsageBuilder Class | CommandLine.OptParse Namespace


UsageBuilder.EndOptions Method

Close the active "options" tag

public void EndOptions();

Remarks

May only be called when a "options" tag is active.

See Also

UsageBuilder Class | CommandLine.OptParse Namespace


UsageBuilder.EndParagraph Method

Close the active "para" tag

public void EndParagraph();

Remarks

May only be called when a "para" tag is active.

See Also

UsageBuilder Class | CommandLine.OptParse Namespace


UsageBuilder.EndSection Method

Close the section

public void EndSection();

Remarks

Section tag must be active

See Also

UsageBuilder Class | CommandLine.OptParse Namespace


UsageBuilder.ToHtml Method

Convert the usage to HTML

public void ToHtml(
TextWriter writer,
OptStyle optStyle,
Uri cssStyleSheet,
bool includeDefaultValues,
string title
);

Parameters

writer
TextWriter to write the output to
optStyle
The style to use when printing possible option names
cssStyleSheet
Stylesheet URI to apply to the HTML content
includeDefaultValues
True to include the default option values in the output
title
Title to use for the HTML page

See Also

UsageBuilder Class | CommandLine.OptParse Namespace


ToText Method

Documentation for the C# command-line option parsing library

UsageBuilder.ToText Method

Convert the usage to Text

Overload List

Convert the usage to Text

public void ToText(TextWriter,OptStyle,bool);

Convert the usage to Text

public void ToText(TextWriter,OptStyle,bool,int);

See Also

UsageBuilder Class | CommandLine.OptParse Namespace


UsageBuilder.ToText Method (TextWriter, OptStyle, Boolean)

Convert the usage to Text

public void ToText(
TextWriter writer,
OptStyle optStyle,
bool includeDefaultValues
);

Parameters

writer
TextWriter to write the output to
optStyle
The style to use when printing possible option names
includeDefaultValues
True to include the default option values in the output

See Also

UsageBuilder Class | CommandLine.OptParse Namespace | UsageBuilder.ToText Overload List


UsageBuilder.ToText Method (TextWriter, OptStyle, Boolean, Int32)

Convert the usage to Text

public void ToText(
TextWriter writer,
OptStyle optStyle,
bool includeDefaultValues,
int maxColumns
);

Parameters

writer
TextWriter to write the output to
optStyle
The style to use when printing possible option names
includeDefaultValues
True to include the default option values in the output
maxColumns
Wrap text at the given column (attempts to wrap at '-' or ' ')

Remarks

if maxColumns is -1, the width of the console will be used on windows machines, and the text will not be wrapped on non-windows machines

See Also

UsageBuilder Class | CommandLine.OptParse Namespace | UsageBuilder.ToText Overload List


UsageBuilder.Transform Method

Convenience method for transforming the XML using a custom XSLT

public void Transform(
TextWriter writer,
XmlReader xsltSource,
XsltArgumentList arguments
);

Parameters

writer
TextWriter to write the output to
xsltSource
Xslt content to use to transform with
arguments
Xslt arguments to pass to the XslTransform

See Also

UsageBuilder Class | CommandLine.OptParse Namespace


UseNameAsLongOptionAttribute Class

Gives the ability to stop the name of a field or property being used to be used as an option name

For a list of all members of this type, see UseNameAsLongOptionAttribute Members.

System.Object
System.Attribute
CommandLine.OptParse.UseNameAsLongOptionAttribute

public class UseNameAsLongOptionAttribute : Attribute

Remarks

By default, the name of a property or field is used as a option name when defined as an option (see OptDefAttribute). This attribute allows only names to be given using LongOptionNameAttribute and ShortOptionNameAttribute attributes. If this attribute value is false, one of the above attributes must be given for the property

Example

Example class implementing options via attributes:

// Example class defining properties
class Properties
{
    #region Enumerations
    internal enum ExamplePropertyEnum
    {
        First,
        Second
    }
    #endregion Enumerations

    #region Members
    private ExamplePropertyEnum _exampleEnumProp;
    #endregion Members

    #region Accessed by code properties
    // Cannot be used by the parser easily, but can be used
    // by code
    public ExamplePropertyEnum ExampleEnumProp
    {
        get { return _exampleEnumProp; }
        set { _exampleEnumProp = value; }
    }
    #endregion Accessed by code properties

    #region Options
    // Cannot be used by the parser easily, but can be used
    // by code
    // The EditorBrowsableAttribute is used to hide this
    // property from code
    [OptDef(OptValType.Flag)]
    [LongOptionName("example-enum-prop")]
    [UseNameAsLongOption(false)]
    [Description("Show how to perform complex type option parsing")]
    [EditorBrowsable(EditorBrowsableState.Never)]
    public string ExampleEnumPropAsString
    {
        get { return _exampleEnumProp.ToString(); }
        set
        {
            switch (value.ToLower())
            {
                case "first": _exampleEnumProp = ExamplePropertyEnum.First; break;
                case "second": _exampleEnumProp = ExamplePropertyEnum.Second; break;
                default:
                    throw new ArgumentException(
                        "Invalid value for the example-enum-prop option");
            }
        }
    }

    // Example of how to reverse flag-option values
    [OptDef(OptValType.Flag)]
    [LongOptionName("no-debug")]
    [UseNameAsLongOption(false)]
    [Description("Disable debug output")]
    [EditorBrowsable(EditorBrowsableState.Never)]
    public bool NoDebug
    {
        get { return !this.Debug; }
        set { this.Debug = !value; }
    }

    [ShortOptionName('b')]
    [OptDef(OptValType.Flag)]
    [LongOptionName("debug")]
    [UseNameAsLongOption(false)]
    [Description("Enable debug output")]
    public bool Debug = false;

    [OptDef(OptValType.ValueReq)]
    [ShortOptionName('d')]
    [LongOptionName("directory")]
    [UseNameAsLongOption(false)]
    [Description("Output directory")]
    [DefaultValue(".")]
    public string Directory = ".";

    [OptDef(OptValType.ValueOpt)]
    [ShortOptionName('f')]
    [LongOptionName("file")]
    [UseNameAsLongOption(false)]
    [Description("Input file")]
    public string File = null;

    [OptDef(OptValType.IncrementalFlag)]
    [ShortOptionName('v')]
    [LongOptionName("verbose")]
    [UseNameAsLongOption(false)]
    [Description("Set level of vebosity for debug printing")]
    public int Verbose = 0;

    [OptDef(OptValType.MultValue, ValueType=typeof(string))]
    [ShortOptionName('s')]
    [LongOptionName("strings")]
    [UseNameAsLongOption(false)]
    [Description("Test option that takes multiple values")]
    public StringCollection Strings = new StringCollection();
    #endregion Options
}

Requirements

Namespace: CommandLine.OptParse

Assembly: CSharpOptParse (in CSharpOptParse.dll)

See Also

UseNameAsLongOptionAttribute Members | CommandLine.OptParse Namespace


UseNameAsLongOptionAttribute Members

UseNameAsLongOptionAttribute overview

Public Instance Constructors

UseNameAsLongOptionAttribute Constructor Constructor

Public Instance Properties

TypeId (inherited from Attribute) | When implemented in a derived class, gets a unique identifier for this Attribute.
UseName | Get if the name should be used as an option

Public Instance Methods

Equals (inherited from Attribute) |
GetHashCode (inherited from Attribute) | Returns the hash code for this instance.
GetType (inherited from Object) | Gets the Type of the current instance.
IsDefaultAttribute (inherited from Attribute) | When overridden in a derived class, returns an indication whether the value of this instance is the default value for the derived class.
Match (inherited from Attribute) | When overridden in a derived class, returns a value indicating whether this instance equals a specified object.
ToString (inherited from Object) | Returns a String that represents the current Object.

Protected Instance Methods

Finalize (inherited from Object) | Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection.
MemberwiseClone (inherited from Object) | Creates a shallow copy of the current Object.

See Also

UseNameAsLongOptionAttribute Class | CommandLine.OptParse Namespace


UseNameAsLongOptionAttribute Constructor

Constructor

public UseNameAsLongOptionAttribute(
bool useName
);

Parameters

useName
Set to false to not use this field or property as a possible option name

See Also

UseNameAsLongOptionAttribute Class | CommandLine.OptParse Namespace


UseNameAsLongOptionAttribute Properties

The properties of the UseNameAsLongOptionAttribute class are listed below. For a complete list of UseNameAsLongOptionAttribute class members, see the UseNameAsLongOptionAttribute Members topic.

Public Instance Properties

TypeId (inherited from Attribute) | When implemented in a derived class, gets a unique identifier for this Attribute.
UseName | Get if the name should be used as an option

See Also

UseNameAsLongOptionAttribute Class | CommandLine.OptParse Namespace


UseNameAsLongOptionAttribute.UseName Property

Get if the name should be used as an option

public bool UseName {get;}

See Also

UseNameAsLongOptionAttribute Class | CommandLine.OptParse Namespace


WarningEventHandler Delegate

Delegate to receive warning events from a parser

public delegate void WarningEventHandler(
Parser sender,
OptionWarningEventArgs e
);

Requirements

Namespace: CommandLine.OptParse

Assembly: CSharpOptParse (in CSharpOptParse.dll)

See Also

CommandLine.OptParse Namespace


CommandLine.ConsoleUtilsHierarchy

Documentation for the C# command-line option parsing library

CommandLine.ConsoleUtils Hierarchy

System.Object
CommandLine.ConsoleUtils.ConsoleHelper
System.ValueType
CommandLine.ConsoleUtils.ConsolePoint
CommandLine.ConsoleUtils.ConsoleRect
CommandLine.ConsoleUtils.ConsoleScreenBufferInfo

See Also

CommandLine.ConsoleUtils Namespace


CommandLine.OptParseHierarchy

Documentation for the C# command-line option parsing library

CommandLine.OptParse Hierarchy

System.Object
CommandLine.OptParse.DefaultUsageInfo ---- CommandLine.OptParse.IProgUsageInfo
CommandLine.OptParse.DictionaryParserHelper ---- CommandLine.OptParse.IOptionContainer, CommandLine.OptParse.IOptionResults
CommandLine.OptParse.EnumDescriptorReader
CommandLine.OptParse.IOptionContainer
CommandLine.OptParse.IOptionResults ---- CommandLine.OptParse.IOptionContainer
CommandLine.OptParse.IProgUsageInfo
CommandLine.OptParse.OptionDefinition
CommandLine.OptParse.OptionResult
CommandLine.OptParse.Parser ---- CommandLine.OptParse.IOptionContainer
CommandLine.OptParse.ParserFactory
CommandLine.OptParse.PropertyFieldParserHelper ---- CommandLine.OptParse.IOptionContainer, CommandLine.OptParse.IOptionResults
CommandLine.OptParse.UsageBuilder
System.Attribute
CommandLine.OptParse.LongOptionNameAttribute
CommandLine.OptParse.OptDefAttribute
CommandLine.OptParse.ShortOptionNameAttribute
CommandLine.OptParse.UseNameAsLongOptionAttribute
System.Collections.DictionaryBase ---- System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable
CommandLine.OptParse.OptionResultsDictionary
System.Delegate ---- System.ICloneable, System.Runtime.Serialization.ISerializable
System.MulticastDelegate
CommandLine.OptParse.WarningEventHandler
System.EventArgs
CommandLine.OptParse.OptionWarningEventArgs
System.Exception ---- System.Runtime.Serialization.ISerializable
System.ApplicationException
CommandLine.OptParse.ParseException
CommandLine.OptParse.InvalidValueException
System.ValueType
System.Enum ---- System.IComparable, System.IConvertible, System.IFormattable
CommandLine.OptParse.DupOptHandleType
CommandLine.OptParse.ListType
CommandLine.OptParse.OptStyle
CommandLine.OptParse.OptValType
CommandLine.OptParse.UnixShortOption
CommandLine.OptParse.UnknownOptHandleType

See Also

CommandLine.OptParse Namespace