Passing Arguments to VS Code when Debugging in C# and .NET

Download full source code.

Most of the time I like working with VS Code, it is faster than Visual Studio and Rider, easier to update, and has many very useful extensions.

But there are times when it is very frustrating to work in, plenty of people have written about this.

Most recently I wanted to debug a C# application that took command line arguments, but there was no obvious way to do this. I kinda remember it being possible a while ago, so I checked the docs but they were not helpful for this.

When I look back at old blog posts of mine I see that there used to be a .vscode directory with a tasks.json and a launch.json file, and in the latter file, I find the args parameter. This is what I need.

I created the directory and files shown above.

In launch.json I add the following -

 1{
 2    "version": "0.2.0",
 3    "configurations": [
 4        {
 5            "name": "My debug config",
 6            "type": "coreclr",
 7            "request": "launch",
 8            "preLaunchTask": "build",
 9            "program": "${workspaceFolder}/bin/Debug/net8.0/DebugPassArguments.exe",
10            "args": ["x", "y", "z"],
11            "cwd": "${workspaceFolder}",
12            "console": "internalConsole",
13            "stopAtEntry": false
14        }
15    ]
16}

There are a couple of things to note here -

  • Line 10 - I can pass in whatever arguments I want.
  • Line 8 - the dependency on the build task, without this your code won’t be recompiled when launching a debug session.

The build task is in the tasks.json file -

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build",
            "command": "dotnet",
            "type": "process",
            "args": [
                "build",
                "/property:GenerateFullPaths=true",
                "/consoleloggerparameters:NoSummary"
            ],
            "problemMatcher": "$msCompile"
        }
    ]
}

Here is a simple application to test it out -

if(args.Length == 0)
{
    Console.WriteLine("You didn't pass in any arguments");
    return;
}

Console.WriteLine("Arguments passed in:");
foreach (var argument in args)
{
    Console.WriteLine($"{argument}");
}

Download full source code.

comments powered by Disqus

Related