Click here to Skip to main content
13,772,325 members
Click here to Skip to main content
Add your own
alternative version


71 bookmarked
Posted 30 Aug 2003
Licenced MIT

Full-featured Automatic Argument Parser

, 5 Nov 2003
Rate this:
Please Sign up or sign in to vote.
Argument parser utility class which makes good use of custom attributes.



What? Yet another argument parsing class?! What for? Well, actually for a couple of reasons:

  • Supports many argument types:
    • Switches (eg. /foo, /foo=1, /foo=true [localized])
    • Named/unnamed flags (eg. -raFl, -aABCDEF). Flags are "type-safe" in the sense that you specify which values are accepted. For example, if the user writes -raFlW and 'W' is not an accepted flag, then an ArgumentFormatException is raised.
    • Named/unnamed values (eg. /foo=bar, "foo")
    • Any prefix(es) you specify (eg. -foo, /foo, \foo, ...)
    • Any assignment symbol(s) (eg. /foo=bar, /foo:bar, ...)
    • Any additional or overriding pattern you provide
  • Automatically sets field/property values according to arguments provided using custom attributes.
    • All value types are supported, including enumerations.
    • You can specify a single member, a class, a type (for static members) or an assembly.
    • One argument can set many members at once, even if located in different types.
  • Supports globalization through custom attributes (ie you provide a ResourceManager, a CultureInfo and a resource ID and the argument name/alias will be automatically updated according to resource file). This works for switches, named values and flags.
  • Keeps track of handled and unhandled arguments.
  • All that in less than 400 lines of code. :)

I want to thank Ray Hayes for his idea of automatically setting field/property by judiciously using custom attributes. This is a great example of that proverbial 1% of inspiration. :) Take a look at his article here.

Quick Example

This is an example quickly showing how you might use the class, more or less taken from the included demo, which by the way is a utility I posted some time ago on this site. You can read the article here.

using Common;
using Common.IO;
using System;
using System.Collections;
using System.Collections.Specialized;
using System.IO;

namespace xmove
    class XMove
        private static System.Resources.ResourceManager m_resMan;

        // this argument can either be named "batch", "file", "batchFile"
        // or even "smurf" if you fancy it
        [AutoSetMember("batch", "file", "batchFile", "smurf")]
        private static String m_batchFile;

        [AutoSetMember("yc", SwitchMeansFalse=true)]
        private static bool m_confirmMove = true;

        [AutoSetMember("yc", SwitchMeansFalse=true)]
        private static bool m_confirmOverwrite = true;
        private static bool m_recursive = false;
        private static FindFile.SearchAttributes m_searchAttributes;
        static void Main(string[] args)
            // a FlagCollection contains all accepted flags
            FlagCollection flags = new FlagCollection();
            // here we add the flag named "a" with accepted values
            // a,c,d,h,...
            // the argument must then looks like "-a<VALUES>" on the command
            // line
            flags.Add("a", "acdehnorstFA");
            // create a new parser that accept all argument formats,
            // is case sensitive and accept provided flags
            ArgumentParser parser = new ArgumentParser(ArgumentFormats.All,
                false, flags);
            // parse the arguments with the result stored in a
            // StringDictionary
            StringDictionary theArgs = parser.Parse(args);

            // automatically set all static members of the class XMove
            // now, the values of m_batchFile, m_confirmMove,
            // m_confirmOverwrite and m_recursive are all set !
            // the corresponding arguments have been moved to
            // parser.HandledArguments
            // the remaining arguments are in parser.UnhandledArguments
            // one argument remains which can't be set automatically
            if (theArgs.ContainsKey("a"))
                String attribs = theArgs[m_resMan.GetString("app0019")];
                if (attribs.IndexOf("A") > -1)
                    m_searchAttributes |= FindFile.SearchAttributes.All;

                if (attribs.IndexOf("F") > -1)
                    m_searchAttributes |= FindFile.SearchAttributes.AnyFile;
            // here we load the resources for the application
            // we then set the resource manager of the
            // AutoSetMemberAttribute accordingly
            // why this property is static is explained in the
            // "How it Works" section of this article
            AutoSetMemberAttribute.Resources = m_resMan;

            // create a new instance of Dummy class
            Dummy dummy = new Dummy();
            // then set members of this class, no matter if they are
            // static, instance, public, private, protected, internal
            // type conversion is done automatically !
        private void LoadResources()
    class Dummy
        public enum MyEnum
        private static int field1;
        // here we indicate that the argument name is to be retrieved using
        // the ResourceManager at runtime
        private Double field2;
        // same here
        protected String Property1
            get {...}
            set {...}
        public MyEnum Property2
            get {...}
            set {...}

Using the code

Two main classes do all the work: ArgumentParser and AutoSetMemberAttribute. As usual, contructors let you directly set one or more properties, so I will skip them.

ArgumentParser class


public char[] AllowedPrefixes [get, set]
The accepted prefix(es).

public ArgumentFormats ArgumentFormats [get, set]<BR>The accepted argument format(s).

public char[] AssignSymbols [get, set]
The accepted assignation symbol(s).

public string CustomPattern [get, set]
An additional or overriding pattern. In the pattern, use capture name constants made public by this class (ArgumentNameCaptureName, ArgumentValueCaptureName, FlagNameCaptureName, FlagsCaptureName and PrefixCaptureName).

public StringDictionary HandledArguments [get]
The argument(s) that have been automatically set by AutoSetMembers method.

public StringDictionary UnhandledArguments [get]
The argument(s) that have not been automatically set by AutoSetMembers method.

public bool UseOnlyCustomPattern [get, set]
Indicates if the custom pattern provided is overriding the internal pattern automatically generated.


public StringDictionary Parse(string[] args)
Parses the array of arguments and returns the dictionary of parsed arguments
UnhandledArgument property is also updated accordingly.

public void AutoSetMembers(Assembly assembly)
public void AutoSetMembers(Type type)
public void AutoSetMembers(object instance)
public void AutoSetMembers(object classToProcess, MemberInfo member)
Automatically sets member(s) of the provided assembly, type, class instance. Also works for a single field/property.

public void Clear()
Clears all saved arguments (both handled and unhandled).

private void BuildPattern()
Builds the pattern to be used when parsing each argument.

private void SetMemberValue(object instance, MemberInfo memberInfo, object value)<BR>Set the static or instance member to the specified value.



public static CultureInfo Culture [get, set]
The culture to be used for retrieving culture aware aliases.

public static ResourceManager Resources [get, set]
The resource manager to be used for retrieving culture aware aliases.

public ArrayList Aliases [get]
Command line argument's name or aliases if many names are possible.

public string Description [get, set]
The description of the command line argument.

public object ID [get, set]
An ID (can be anything you want).

public string ResID [get, set]
The resource ID to be used when retrieving culture aware aliases.

public bool SwitchMeansFalse [get, set]
Indicates if the meaning of a switch is false instead of true as usual.

How it Works

Parsing of the command line

Here is a quick explanation of the regex that is constructed by ArgumentParser.BuildPattern() private method. Variables are indicated by capitalized names and are to be replaced at runtime.

// The whole parsing string (with all possible argument formats) :
// ---------------------------------------------------------------
// |(^(?<PREFIX>[PREFIXES])(?<FLAGNAME>)FLAG_NAMES)(?<FLAGS>[FlagsCaptureName]+)$)
// Again, but commented :
// ----------------------
// (CUSTOM_PATTERN)|        # custom pattern, if any (it has priority over
//                          # standard pattern)
// foreach flag in FlagCollection :
// (^
// (?<PREFIX>[PREFIXES])            # mandatory prefix
// (?<FLAGNAME>)FLAG_NAMES)       # flag name
// (?<FLAGS>[FlagsCaptureName]+)  # flag value
// $)|
// (^
// (?<PREFIX>[PREFIXES])            # mandatory prefix
// (?<NAME>[^EQUAL_SYMBOLS]+)     # argument name (which includes flag
//                                # name/values)
// ([EQUAL_SYMBOLS](?<VALUE>.+))? # argument value, if any
// $)
// |(
// LITERAL_STRING_SYMBOL?   # optional @ caracter indicating literal string
// (?<VALUE>.*)             # standalone value (will be given an index when
//                          # parsed in Parse() method)
// )

Automatically setting member values

At design time, AutoSetMemberAttribute custom attribute is used to specify which argument will be used to set the affected member. Other informations include description, resource ID and an ID that you might use at your convenience.

At runtime, you can set the AutoSetMemberAtttribute static properties Resource and Culture. It's necessary to make those properties static because attributes are serialized at compile time, so they can only have constant values as instance properties.

When you execute ArgumentParser.SetAutoMembers(...), the following occurs :

  1. AutoSetMember attributes will be located using reflection.
  2. If a resource ID is specified and a resource manager and a culture are provided, the localized argument name will be added as an alias.
  3. The argument associated to the member (if any) will be converted to the member's type
  4. The member's value will be updated using ArgumentParser.SetMemberValue(...).
  5. The argument will be removed from ArgumentParser.UnhandledArguments and added to ArgumentParser.HandledArguments.
/// Automatically sets members for the provided
/// <SEE cref="System.Reflection.Assembly" />.
/// </SUMMARY>
/// <PARAM name="assembly">The <SEE cref="System.Reflection.Assembly" /> to process.</PARAM>
public void AutoSetMembers(Assembly assembly)
    Type[] types = assembly.GetTypes();

    foreach (Type type in types)

/// Automatically sets members for the provided <SEE cref="System.Type" />.
/// </SUMMARY>
/// <PARAM name="type">The <SEE cref="System.Type" /> to process.</PARAM>
/// <REMARKS>Only static members will be processed.</REMARKS>
public void AutoSetMembers(Type type)
    MemberInfo[] members = type.FindMembers(
        AutoSetMemberAttribute.SupportedBindingFlags, Type.FilterName, "*");

    foreach (MemberInfo member in members)
        AutoSetMembers(type, member);

/// Automatically sets members for the provided class instance.
/// </SUMMARY>
/// <PARAM name="instance">The class instance to process. Must not be null.</PARAM>
/// <REMARKS>Both static and instance members will be processed.</REMARKS>
public void AutoSetMembers(object instance)
    MemberInfo[] members = instance.GetType().FindMembers(
        AutoSetMemberAttribute.SupportedBindingFlags, Type.FilterName, "*");

    foreach (MemberInfo member in members)
        AutoSetMembers(instance, member);

/// Automatically sets member of the provided class instance or
/// <SEE cref="System.Type" />.
/// </SUMMARY>
/// <PARAM name="classToProcess">The class instance or <SEE cref="System.Type" /> to process.</PARAM>
/// <PARAM name="member">The member which will be set. Must be a field or a property.</PARAM>
/// <REMARKS>Both static and instance members are accepted.</REMARKS>
public void AutoSetMembers(object classToProcess, MemberInfo member)
    AutoSetMemberAttribute attrib = Attribute.GetCustomAttribute(member,
        typeof(AutoSetMemberAttribute)) as AutoSetMemberAttribute;

    if (attrib != null)
        if (attrib.ResID != null && AutoSetMemberAttribute.Resources != null)
                attrib.ResID, AutoSetMemberAttribute.Culture));

        String argValue = null;
        bool found = false;

        foreach (String alias in attrib.Aliases)
            if (m_unhandled.ContainsKey(alias))
                argValue = (String)m_unhandled[alias];

                m_handled.Add(alias, argValue);

                found = true;
            else if (m_handled.ContainsKey(alias))
                argValue = (String)m_handled[alias];

                found = true;

        if (found)
            Type memberType = null;

            switch (member.MemberType)
                case MemberTypes.Property:
                    memberType = ((PropertyInfo)member).PropertyType;

                case MemberTypes.Field:
                    memberType = ((FieldInfo)member).FieldType;

            if (memberType == typeof(bool))
                if (argValue == "")
                    SetMemberValue(classToProcess, member,
                else if (argValue == Boolean.FalseString ||
                    argValue == Boolean.TrueString)
                    SetMemberValue(classToProcess, member,
                    // last chance ... if can't parse it as integer, an
                    // exception will be raised
                    SetMemberValue(classToProcess, member,
                        Int32.Parse(argValue) != 0);
            else if (memberType == typeof(String))
                SetMemberValue(classToProcess, member, argValue);
            else if (memberType.IsEnum)
                object value = Enum.Parse(memberType, argValue,
                SetMemberValue(classToProcess, member, value);
            else if (memberType.IsValueType)
                SetMemberValue(classToProcess, member,
                    Convert.ChangeType(argValue, memberType));

/// Sets the static or instance member (property or field) to the specified
/// value.
/// </SUMMARY>
/// <PARAM name="instance">The class instance or <SEE cref="System.Type" /> to be used.</PARAM>
/// <PARAM name="memberInfo">The member to be set.</PARAM>
/// <PARAM name="value">The new value of the member.</PARAM>
private void SetMemberValue(object instance, MemberInfo memberInfo,
    object value)
    if (memberInfo is PropertyInfo)
        PropertyInfo pi = (PropertyInfo) memberInfo;

        if (pi.CanWrite)
            MethodInfo methodInfo = pi.GetSetMethod(true);

            BindingFlags bindingFlags = BindingFlags.SetProperty;

            if (methodInfo.IsStatic)
                bindingFlags |= BindingFlags.Static;

            pi.SetValue(instance, value, bindingFlags, null, null, null);
    else if (memberInfo is FieldInfo)
        FieldInfo fi = (FieldInfo) memberInfo;

        BindingFlags bindingFlags = BindingFlags.SetField;

        if (fi.IsStatic)
            bindingFlags |= BindingFlags.Static;

        fi.SetValue(instance, value, bindingFlags, null, null);


This article, along with any associated source code and files, is licensed under The MIT License


About the Author

Sebastien Lorion
Canada Canada
Sébastien Lorion is software architect as day job.

He is also a musician, actually singing outside the shower Smile | :)

He needs constant mental and emotional stimulation, so all of this might change someday ...

You may also be interested in...

Comments and Discussions

Generalhiiiiiiiiii Pin
glory44415-Apr-11 9:58
groupglory44415-Apr-11 9:58 
QuestionHow get a regular parameter rather than an option? Pin
DaveKolb2-Apr-09 21:00
memberDaveKolb2-Apr-09 21:00 
AnswerRe: How get a regular parameter rather than an option? Pin
Sebastien Lorion3-Apr-09 6:27
memberSebastien Lorion3-Apr-09 6:27 
GeneralRe: How get a regular parameter rather than an option? Pin
DaveKolb3-Apr-09 9:31
memberDaveKolb3-Apr-09 9:31 
AnswerRe: How get a regular parameter rather than an option? Pin
Sebastien Lorion3-Apr-09 10:06
memberSebastien Lorion3-Apr-09 10:06 
GeneralRe: How get a regular parameter rather than an option? Pin
DaveKolb3-Apr-09 10:15
memberDaveKolb3-Apr-09 10:15 
AnswerRe: How get a regular parameter rather than an option? Pin
Sebastien Lorion3-Apr-09 10:35
memberSebastien Lorion3-Apr-09 10:35 
AnswerRe: How get a regular parameter rather than an option? Pin
Sebastien Lorion4-Apr-09 18:59
memberSebastien Lorion4-Apr-09 18:59 
GeneralRe: How get a regular parameter rather than an option? Pin
DaveKolb4-Apr-09 20:58
memberDaveKolb4-Apr-09 20:58 
QuestionSuggestion Pin
exbuddha16-Oct-06 11:14
memberexbuddha16-Oct-06 11:14 
AnswerRe: Suggestion Pin
Sebastien Lorion16-Oct-06 11:21
memberSebastien Lorion16-Oct-06 11:21 
GeneralRe: Suggestion Pin
exbuddha16-Oct-06 13:32
memberexbuddha16-Oct-06 13:32 
QuestionUse the same switch twice Pin
Armus15-Sep-06 2:57
memberArmus15-Sep-06 2:57 
AnswerRe: Use the same switch twice Pin
Sebastien Lorion15-Sep-06 4:58
memberSebastien Lorion15-Sep-06 4:58 
QuestionDoes the code check for invalid options? Pin
Josef Meile15-Feb-05 10:30
memberJosef Meile15-Feb-05 10:30 
AnswerRe: Does the code check for invalid options? Pin
Sebastien Lorion17-Feb-05 3:50
memberSebastien Lorion17-Feb-05 3:50 
GeneralAutoSetMember for VB.NET? Pin
mike2orb23-Jan-04 19:04
membermike2orb23-Jan-04 19:04 
GeneralRe: AutoSetMember for VB.NET? Pin
Guy LaRochelle29-Nov-04 3:27
memberGuy LaRochelle29-Nov-04 3:27 
QuestionWhy GPL? Pin
godefroi5-Nov-03 12:39
membergodefroi5-Nov-03 12:39 
AnswerRe: Why GPL? Pin
Sebastien Lorion5-Nov-03 20:17
memberSebastien Lorion5-Nov-03 20:17 
GeneralLooks Great Pin
William Bartholomew7-Sep-03 12:48
memberWilliam Bartholomew7-Sep-03 12:48 
GeneralRe: Looks Great Pin
Sebastien Lorion7-Sep-03 16:36
memberSebastien Lorion7-Sep-03 16:36 
GeneralBest argument parser yet Pin
scadaguy5-Sep-03 4:10
memberscadaguy5-Sep-03 4:10 
GeneralRe: Best argument parser yet Pin
Sebastien Lorion5-Sep-03 13:10
memberSebastien Lorion5-Sep-03 13:10 
GeneralGreat Utility - One Suggestion Pin
Heath Stewart5-Sep-03 3:30
protectorHeath Stewart5-Sep-03 3:30 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web02 | 2.8.181119.1 | Last Updated 6 Nov 2003
Article Copyright 2003 by Sebastien Lorion
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid