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

徘徊边缘 提交于 2019-12-04 03:07:23

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

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

Changing it from:

  "console": "internalConsole",

To:

  "console": "externalTerminal",

fixed it for me.

It will show your output if you will press ctrl+F5. You will get the output in console window. Another solution, if you will write Console.ReadLine(); after console.writeline, it will remain open console window until you will not press any key.

You need to add any one of following line code

Console.Readline()
Console.Read()
Console.ReadKey()

example:

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

The code did compile and then run but it wen't very fast and the console application closed itself after the execution. To prevent this from happening you need to add another method like:

  • Console.Read();

or

  • Console.ReadLine();

(The Line stands for linefeed, that means that the cursor moves to the next line to the left).

This way, the application will close if you press the 'enter' key on your keyboard.

Nizam Ali

You need to do this

Console.WriteLine("Hello");
string name = Console.ReadLine();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!