Make a console application in C#

[console]

A console application doesn’t have a real user interface. Instead it communicates with the user via a text-only console window. It can display text and read input from the keyboard.

To make a console application, start a new project by pressing Ctrl-Shift-N or by selecting File > New and selecting Project. On the New Project dialog, select the Console Application template, give it a good name, and click OK. Initially the new program will look like something this:

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

namespace howto_console_app
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}

The included using statements may vary depending on your version of Visual Studio.

Add code to the Main method. Use Console.Write and Console.WriteLine to display output. Use Console.Read and Console.ReadLine to get input. The following code shows a simple program that displays the date and then waits for the user to press Enter before continuing.

static void Main(string[] args)
{
    Console.WriteLine(DateTime.Now.ToString());
    Console.Write("Press any key to continue");
    Console.ReadLine();
}

Probably the most common mistake when making a console application is not waiting for the user to read the output. When the Main method ends, the program exits. If you only use Console.WriteLine to display output, the program will very quickly display its output, Main will end, and the program will disappear before the user has a chance to read the results. Either use a timer to delay ending or use Console.ReadLine as in this example to give the user a chance to view the output.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in console and tagged , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

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