Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Console.WriteLine work in Visual Studio Code?

I have scriptcs and coderunner installed on Visual Studio Code. When I run a simple program that includes Console.WriteLine("Test") I don't see any output. The program seems to run successfully and exits with code 0.

Any suggestions?

Here's all the code in case anyone is interested:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Test");
    }
}
like image 445
Matt West Avatar asked Apr 05 '17 16:04

Matt West


People also ask

How do I get console WriteLine output in Visual Studio?

In Visual Studio uppermost menu choose Debug > Windows > Output. It shows all Console. WriteLine("Debug MyVariable: " + MyVariable) when you get to them.

How do I print from console WriteLine?

By using: \n – It prints new line. By using: \x0A or \xA (ASCII literal of \n) – It prints new line. By using: Console. WriteLine() – It prints new line.

What is console WriteLine () in C#?

WriteLine(String, Object, Object) Writes the text representation of the specified objects, followed by the current line terminator, to the standard output stream using the specified format information. WriteLine(String)


2 Answers

In launch.json there should be a field called 'console':

Changing it from:

  "console": "internalConsole",

To:

  "console": "externalTerminal",

fixed it for me.

like image 118
Tim Avatar answered Oct 07 '22 18:10

Tim


If you are just trying to run a cs file without a project etc then the problem is that code runner is treating the file as a script. As such the main method is actually not being invoked as it would be if running a console app.

The solution therefore is to make your main method public and add a call to Program.Main(null); after the class definition. This solution does not require any launch.json config file or config changes. Note the call to Program.Main after the class definition does show as an error in VS code but it runs fine in code runner. See the code block below.

using System;
class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Test");
    }
}

Program.Main(null);

I found the answer to this here: https://stackoverflow.com/a/46179597

like image 36
Kevin Avatar answered Oct 07 '22 17:10

Kevin