Console applications are great. They’re convenient little workers that don’t need fancy GUIs and complex APIs. They just get on with the tasks you lay out for them. They’re a great choice for standalone apps or layers of an overall architecture that need to act like an ‘engine’ or a ‘black box’, with data going in, being processed and then being outputted to a source of your choosing.

The ‘data going in’ aspect of console applications is what I’d like to discuss in this post. Normally, the arguments that go into a a console app are command-line based. After all, when we start a console app, we’re starting a Windows process (or executable) and if you were doing this via the command line, we’d type the full qualified file path of the app into our command prompt, followed by the arguments to be passed in, separated by a space.

This is still testable while in development, but not in the way you may want it to be. What if you want to start the app, passing in specific argument values, and then hit breakpoints and step through the code? Using the method described above would make this difficult, as Visual Studio doesn’t have any debug symbols attached to the newly running process at that point, and therefore it cannot breakpoint the app.

You would want to start the app from Visual Studio instead of from the command line, and whilst doing it, tell Visual Studio what arguments you are passing in, just as you would if you were calling the app from the command line. Luckily, this has been a feature in Visual Studio for quite some time, but you may not have come across it if you’re new to console application development in .NET.

Adding Command Line Arguments at Runtime

  1. In your console app project, within Visual Studio, right click your project in the Solution Explorer and click ‘Properties’
  2. In the properties screen, go to ‘Debug’ and then ‘General’. You’ll see an option to ‘Open debug launch profiles UI.’ Click it

3. Upon opening the launch profiles screen, you’ll the first option is the one where you can add your command line arguments. Add your arguments, separating them with a space. In my example, I’m going to be passing the string argument ‘arg2’ so that my console app’s ‘Main()’ method routes the logic to a specific method based on the argument.

Now, when I start my console app, it will run in debug, allowing me to step through the code with breakpoints, but it will also pass in the ‘arg2’ string argument to the entry point of the app.

Here’s my main method:

When passing in ‘arg2’, I’d expect the switch statement to call runMethod2(). Which, after running the app, I can see happening in debug:

Want more C# tips and tricks? Subscribe to my mailing list, or contact me.

author image

About NIck

Leave a Reply

Your email address will not be published. Required fields are marked *

You Might Also Like...