Layout of a Typical Visual C# Program

Layout of a Typical Visual C# Program

Let’s take a closer look at the HelloWorld project created in the previous section. Although this program is quite simple, it demonstrates the basic principles of developing programs using Visual C#. As mentioned, the HelloWorld solution includes one project, also named HelloWorld. The HelloWorld project contains a Visual C# source file named Class1.cs, which is shown here:

using System;
namespace HelloWorld
{
    /// <summary>
    /// Summary description for Class1
    /// </summary>
    class Class1
    {
        static void Main(string[] args)
        {
            //
            // TODO: Add code to start application here.
            //
        }
    }
}

This Visual C# code listing shows Class1.cs as it’s generated by the Visual C# project template. This is a basic Visual C# console-mode program; as written, it does nothing except start and exit. We’ll add some enhancements to the program in the following sections. For now, let’s look at the program as is.

Commenting Your Source

One of the first things you might notice is that comment lines in C# begin with two or more slashes. It is also possible to use comment blocks as in C and C++. Comment blocks begin with /* and end with */. The region inside a comment block can span multiple lines, like this:

/*
    HelloWorld – a simple C# example by Mickey Williams
*/

Comment blocks can’t be nested.

Using Documentation Comments

You might have noticed that one section of the source code has comments that begin with three slashes. This is a documentation comment. Documentation comments are one of the new features of the Visual C# .NET editor. These comments can be extracted during compilation to create documentation for your project.

Two types of documentation can be generated, as follows:

  • An XML document that includes detailed information about the current solution. This XML can be processed using standard XML techniques to perform searches or even transformation into other documentation formats.

  • A set of HTML pages that describe your solution, including cross-references among the different solution elements, with separate files for different solution elements.

To create documentation comments, simply move to the line above any type, namespace, method, or variable declaration and type three slashes above the program element you’re commenting about, as shown here:

///

The editor will automatically create a comment block for you. A comment block for a public or an internal method declaration will include parameter names and return values. The editor inserts comment tags in XML format, with each tag identifying some part of the source element that’s documented by the comments.

Extracting Documentation Comments

To generate documentation pages for your solution, choose Build Comment Web Pages from the Tools menu. By default, the Build Comment Web Pages dialog box is configured to generate comments for the entire solution. If your solution has multiple projects, you can pick one or more projects from the solution to have its comments generated. You also can specify a directory that will receive the generated Web pages.

The Build Comment Web Pages dialog box also enables you to add the start page for the documentation to your Internet Explorer Favorites list. Click OK to generate the documentation. The documentation start page will be displayed inside Visual Studio .NET, and you can immediately start browsing your documentation pages.

Extracting the raw XML documentation is slightly more complex. You must first open the Property Pages dialog box for the project by right-clicking the project’s icon in Solution Explorer and choosing Properties from the shortcut menu. Select the Build category in the Configuration Properties folder. Enter the name of the XML file as the XML Documentation File property. This path is project-relative. Each time your project is compiled, this file will be rebuilt if required. The XML file will be rebuilt whenever changes to your source code should be reflected in the XML documentation.

Using Namespaces

Namespaces are used two ways in the HelloWorld project. The following line enables simplified use of types found in the .NET Framework’s System namespace:

using System;

Additionally, a new namespace for the HelloWorld project is created with this code:

namespace HelloWorld
{
    
    

}

The Visual C# project template creates a namespace that contains all of your project’s types. This helps to insulate any types you create from types that might exist elsewhere in the .NET Framework. When you declare new types in your applications, you should declare them within a unique namespace, as the Console Application template did here. Namespaces are discussed in more detail in Chapter 2.

Declaring a Class

When you’re programming in C#, all code executes within a class—there are no global functions or methods in C#. The Visual C# project template has created a class for us and named it Class1. (We’ll rename it with a more meaningful name later in this chapter, in the section “Providing Output for Hello World.”)

Classes are declared using the class keyword, followed by the name of the class, as shown here:

class Class1
{
    
    

}

All declarations of methods, types, and member variables made within the curly braces that follow the class name are members of the class. Classes and their declaration syntax are discussed in more detail in Chapter 2. For now, it’s enough to understand that a C# class usually contains data members and methods. In this case, Class1 defines a single method named Main.

Defining a Main Method

Every console-mode application has a Main method that serves as the entry point (or starting point) for your application. Although it’s possible to have more than one method named Main in a project, there’s no reason to do so, and you’d be required to specify which of the methods is the real entry point for your application.

Main can be defined in any of the following ways:

static void Main(string[] args)
{
    // No return value; accepts command-line parameters
}


static int Main(string[] args)
{
    // Returns integer value; accepts command-line parameters
}


static void Main()
{
    // No return value; no command-line parameters
}


static int Main()
{
    // Returns integer value; no command-line parameters
}

Keep in mind that C# is a case-sensitive language—although Main is a valid name, main and MAIN aren’t. The two versions of Main that accept command-line arguments include a parameter declaration for a variable named args. Using command-line arguments as parameters passed to Main is discussed in Chapter 5.

Compiling Your Project

At this point, you can compile your solution by choosing Build Solution from the Build menu or by pressing Ctrl+Shift+B. The compilation should be successful, as shown in the output window, which should look something like this:

Build started: Project: HelloWorld, Configuration: Debug .NET

Preparing resources...
Updating references...
Performing main compilation...

Build complete -- 0 errors, 0 warnings
Building satellite assemblies...

---------------------- Done ----------------------

    Build: 1 succeeded, 0 failed, 0 skipped

This output shows that a debug compilation, or build, of the HelloWorld project was started and that the build was completed with no warnings or errors. The output assembly is placed in the bin\debug subdirectory of your project’s directory and will be named HelloWorld.exe.

You can execute this program either on the command line or through Windows Explorer; however, the Hello World program doesn’t actually do anything yet. In the next section, we’ll add an output statement.

Providing Output for Hello World

The first step I take with my projects is to give the classes meaningful names. Class1 is a perfectly valid name for a C# class, but it doesn’t really help describe the class’s purpose. Because the class contains the entry point for the Hello World application, I’ve renamed it HelloWorldApp. The following code also has additional comments and an output statement that displays Hello World on the console:

using System;

namespace HelloWorld
{
    /// <summary>
    /// A C# version of Hello World!
    /// </summary>
    class HelloWorldApp
    {
        static void Main(string[] args)
        {
            // Display a hello message.
            Console.WriteLine("Hello, World!");
        }
    }
}

This version of Hello World displays a message in the command-line screen or console by executing the following line:

Console.WriteLine("Hello, World!");

This line of code invokes the WriteLine method of the Console class and passes a string as a parameter. String literals such as “Hello, World!” are always enclosed in quotation marks. The WriteLine method offers many options for displaying and formatting text output. In the next few chapters, you’ll use the Console class for accepting input from the user as well as writing output to the user.



Part III: Programming Windows Forms