Thursday, January 03, 2008
A command line interface base class

I needed a simpler way build basic command line interfaces so I cobbled together a useful C# base class.

I made the class as simple as possible to create entry point (start up) classes.


class Program :BaseConsole {

    public override string Name {
        get { return "Console Application"; }
    }

    protected override void LoadCommands() {
        this.Commands.Add("print", () => Console.WriteLine("print out"));
        this.Commands.Add("another", () => Console.WriteLine("another print out"));
    }

    static void Main(string[] args) {
        new Program().Run();
    }
}


 
 
Just run a console application that starts the Main() of the Program class. Typing in any commands that have been added to Commands will invoke the associated action.
 
Console Application
=====================================
Type 'help' to get available commands
Type 'exit','done' or 'quit' to exit

>>print
print out

>>another
another print out

>>
 
If you type "help" it will print a list of available commands. You can exit the program by typing "exit","quit" or "done".
 
The commands themselves are stored in a Dictionary<string,Action> - the new lambdas in C# 3 make writing inline functions so simple.
 

Download it here.

kick it on DotNetKicks.com

Tags: ,

posted @ Thursday, January 03, 2008 6:51 AM | Feedback (4)
Posts
8
Comments
28
Trackbacks
0