Home Forums Programming General C# - Passing parameters on launch RE: C# - Passing parameters on launch

  • This is more a question of code organisation -- something that only improves with practice.

    Remember that you can create as many classes as you need to run your application (i.e. you can have more than Program and Form1, if it better organises your code).

    For instance, in an app of this type, I might have a class that represents all the arguments that can be passed to the command-line, like follows:

    public static class Options

    {

    public static void ParseArguments(IEnumerable<string> args)

    {

    ConnectionString = null;

    TestMode = false;

    int iter = 0;

    foreach (string arg in args)

    {

    if (iter == 0)

    {

    Connection = ConfigurationManager.ConnectionStrings[arg];

    if (string.IsNullOrEmpty(Connection)) throw new Exception("Invalid Connection argument");

    }

    else if (iter == 1)

    {

    TestMode = string.Equals(arg, "test");

    }

    iter++;

    }

    }

    public static bool TestMode { get; private set; }

    public static string ConnectionString { get; private set; }

    }

    In my Main function (the first place I can see the command-line args) I would initialise the class:

    void Main(string[] args)

    {

    Options.ParseArguments(args);

    Application.Run(new Form1());

    }

    ...and then, everywhere else in my code, whenever I needed access to a command-line arg, I could reference Options:

    void Button1_Click(object sender, EventArgs e)

    {

    if (Options.TestMode) MessageBox.Show("I am testing");

    using (IDbConnection conn = new SqlConnection(Options.ConnectionString))

    {

    using (IDbCommand cmd = conn.CreateCommand("SELECT * FROM my_table"))

    {

    using (IDataReader reader = cmd.ExecuteReader())

    {

    while (reader.Read())

    {

    // ... do stuff for each row

    }

    }

    }

    }

    }

    You don't have to structure it like I have (I myself probably wouldn't use statics), nor do you have to write your own parsing routines -- there are plenty other ways to do it, if that approach seems like too much hard work (including pre-written libraries to handle command-line arguments). Google is your friend.

    Good luck.

    J.