First console application

Creating your first Console Application

Now that we know all the basic information about the architecture of the .NET Framework, it is time for some coding. Finally! Let us create our very first .NET Framework application. For this we will use Visual Studio.

There are many types of .NET Framework applications that you can create in Visual Studio. The most basic one is the Console application.

The Console application allows to display and read data from the user through a simple black and white console. Even though this type of application is not the one most commonly used, we will use it to demonstrate most of the C# language capabilities in this topic.

So, without further ado, let us fire up Visual Studio and create a new C# Console application.

Everything in Visual Studio is considered a project and our Console application is no exception. To create a new project in Visual Studio go to the File menu and select New > Project.

New project dialog

Visual Studio opens up a “New Project” dialog. Make sure you select “Visual C#” as your language and “Console Application” as the type of the project. At the bottom of the dialog you can specify the name of the project, its location and the name of a solution.

The solution itself only provides a way to put several projects into one group inside Visual Studio. The project, on the other hand, is more important. Almost every project gets in the end compiled into an executable or a DLL library.

In our example we will name both the project and the solution “MyCSharpDotNet.FirstConsoleApplication” and click OK.

This will create a project for our Console application named “MyCSharpDotNet.FirstConsoleApplication” and as every project needs to be part of a solution a new solution with the same name will also be created.

Once Visual Studio creates and opens up the new project, you will notice two important windows. The window called “Solution Explorer” shows the newly created solution and its project. It also shows all the items and files they contain. The second window shows the content of an automatically created “Program.cs” file.

The “Program.cs” is a code file and already contains the basic code for the application to run. In fact, you can already have the application compiled and run it. To try this out use the “Start” command located in the application toolbar or just press F5.

Once the application starts a new console window appears. Since we have not yet programmed any functionality to our console application, the console window also immediately closes.

Usings, namespaces and classes

Before we get wild and start coding our new application, let us first look at the already generated code.

The code starts with multiple using statements:

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

And then everything else is scoped within a “Program” class and that itself is then scoped inside a namespace declaration:

namespace MyCSharpDotNet.FirstConsoleApplication
{
    class Program
    {
        ...
    }
}

Every functionality in C# .NET Framework needs to be written inside a class. Each class is defined by its name. The class name has to be unique in order to access the class from other parts of the code. As there are already many classes defined in the .NET Framework itself (in the Base Class Libraries) and other developers also add their own classes, it would be very difficult to keep choosing new and new unique class names. This is where namespace comes in handy. Once a class is scoped to a namespace its name than needs to be unique only within that namespace.

To access a class from inside the same namespace, only the class name suffices as it is unique inside that namespace. To access the class from another namespace, the class has to be qualified not only by its name but also by its namespace. In our example, the “Program” class would have to be qualified as “MyCSharpDotNet.FirstConsoleApplication.Program”.

It is generally recommended to use at least two blocks for a namespace – in real world applications this could be for example something like “CompanyName.ModuleName”. The fully qualified name of the class would then be “CompanyName.ModuleName.ClassName”.

To show you another example, let us use one of the classes contained in the .NET Framework Base Class Libraries. Its name is StringBuilder and it is defined in the “System.Text” namespace. If we were to use this class inside our namespace we would need to qualify it fully as “System.Text.StringBuilder”.

If we frequently use classes from other namespaces, we can take advantage of the “using” statement. The “using” statement saves us some typing as it tells the .NET Framework compiler to look for classes not only inside our own the namespace but also inside the namespaces defined by the “using” statements.

As you can see, Visual Studio already created a using statement for “System.Text” namespace in our “Program.cs” file. In order to use the StringBuilder class in our “Program.cs” file, only the class name “StringBuilder” will suffice. If the compiler fails to find the class name in our namespace, it will then continue to search for it in all the namespaces defined by “using” statements and it will eventually find it. If we were to remove the “using”, the compiler would then not be able to find the “StringBuilder” class and a full qualification “System.Text.StringBuilder” would have to be used.

The Main method

Our “Program” class already has a “Main” method:

static void Main(string[] args)
{
}

The word “Main” is reserved and there can only be one method of this name in the entire application. The .NET runtime searches for the method of this name and executes it right after the application starts.

There are couple things to note about the main method. First, it is prefixed by a “static” keyword. This basically means that the method can be called directly on the “Program” class without a need to first create its instance.

The “void” keyword denotes that the method doesn’t return any result. It will only execute the code that lies inside it.

In parenthesis the main method defines that it expects one parameter – a string array of arguments. These arguments can be passed to the console application from a command line as such: MyCSharpDotNet.FirstConsoleApplication.exe “Parameter1”, “Parameter2”.

When we start the application from within Visual Studio, there are no parameters passed to the method and the string array is empty (null).

The main method can actually have three more forms (signatures) that it can use. It all depends on whether the method accepts a parameter or whether it returns a whole number (integer). These are all of the four possible signatures:

static void Main()
static void Main(string[] args)
static int Main()
static int Main(string[] args)

Console class

To manipulate the console from within the application, we can use many static methods of a “Console” class. Let us now take a look at two of them.

To gather an input from the user, we can use the ReadLine method. The following code shows how to read a single line from the console and save it into a string variable called “input”.

string input = Console.ReadLine();

To write any information on the console we can use the WriteLine method. The WriteLine method has many signatures. One of them allows to pass a string to be written on the console as a parameter. The following code writes “Hello!” on the console:

Console.WriteLine("Hello!");

The following Main method shows both of these examples at work:

static void Main(string[] args)
{
    // Ask user to provider their name
    Console.WriteLine("Please insert your name: ");
    string input = Console.ReadLine();
 
    // Write one empty line for nice formatting
    Console.WriteLine();
 
    // Greet the user with their name
    Console.WriteLine("Hello " + input + "!");
            
    // Wait for user input
    Console.ReadLine();
}

The example shows a couple more interesting things. Any line prefixed with double slashes “//” will be ignored by the compiler and can contain the developer’s comments.

Two or more strings can be joined together (concatenated) using the plus “+” sign.

To prevent the console application from finishing before the user had a chance to read the output, another ReadLine method is added at the end. This way the console application waits for the user’s input – even though it does not process it in any way.

You can see the result by running the application from within Visual Studio – again select “Start” in the toolbar or press F5.

Console

First Console application is also available for download.

Continue to: Data types

Go up to: Basics


Should you have any questions or found a mistake that needs correcting, feel free to send an email to: info [at] mycsharp [dot] net


Advertisements :