Basic C# Console Application Structure
Let's take a closer look at the console application example from Chapter 2 (ConsoleApplication1), and break down the structure a bit. Here's the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// Output text to the screen.
Console.WriteLine(″The first app in Beginning C# Programming!″);
Console.ReadKey();
}
}
}
You can immediately see that all the syntactic elements discussed in the previous section are present here—semicolons, curly braces, and comments, along with appropriate indentation.
The most important section of code at the moment is the following:
static void Main(string[] args)
{
// Output text to the screen.
Console.WriteLine(″The first app in Beginning C# Programming!″);
Console.ReadKey();
}
This is the code that is executed when you run your console application. Well, to be more precise, the code block enclosed in curly braces is executed. The comment line doesn't do anything, as mentioned earlier; it's just there for clarity. The other two code lines output some text to the console window and wait for a response, respectively, though the exact mechanisms of this don't concern us for now.
Note how to achieve the code outlining functionality shown in the previous chapter, albeit for a Windows application, since it is such a useful feature. You can do this with the #region and#endregion keywords, which define the start and end of a region of code that can be expanded and collapsed. For example, you could modify the generated code for ConsoleApplication1 as follows:
#region Using directives using System; using System.Collections.Generic; using System.Linq; using System.Text; #endregion
This enables you to collapse this code into a single line and expand it again later should you want to look at the details. The using statements contained here, and the namespace statement just underneath, are explained at the end of this chapter.
Note |
|---|
|
Any keyword that starts with a # is actually a preprocessor directive and not, strictly speaking, a C# keyword. Other than the two described here, #region and #endregion, these can be quite complicated, and they have very specialized uses. This is one subject you might like to investigate yourself after you have worked through this book. |
For now, don't worry about the other code in the example, because the purpose of these first few chapters is to explain basic C# syntax, so the exact method of how the application execution gets to the point where Console.WriteLine() is called is of no concern. Later, the significance of this additional code is made clear.
Programming 2015 -2016
Note