user7454355
user7454355

Reputation:

Visual Studio execution closes when pressing enter

Hello im trying to learn C# step by step. I installed Visual Studio to practice but 20 mins in I cant test my basic code when executing:

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

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("What is your name?");
            string name = Console.ReadLine();
            Console.WriteLine("My name is " + name);
        }
    }
}

It is as basic as this but when I execute and type a name and press enter, the cmd just closes. any help would be appreciated because i am enthusiastic to start out with C#

cmd

Upvotes: 3

Views: 2033

Answers (3)

Saurin Vala
Saurin Vala

Reputation: 1928

Try Ctrl + F5

If you don't need to debug, then Ctrl-F5 is the best option

works automatically without any Console.Readline() or ReadKey()

Visual Studio will keep the console window open, until you press a key.

Upvotes: 0

PepitoSh
PepitoSh

Reputation: 1836

The Main method returns after

Console.WriteLine("My name is " + name);

And this effectively terminates the app. You should put a

Console.Read();

to wait until the next keystroke.

Upvotes: 3

Mirko Acimovic
Mirko Acimovic

Reputation: 506

Add another input to close application, so cmd wont close until you press enter again.

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

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("What is your name?");
            string name = Console.ReadLine();
            Console.WriteLine("My name is " + name);
            Console.ReadLine();
        }
    }
}

Upvotes: 1

Related Questions