Saying “Hello, World!”

The programming world has a surprising number of well-established traditions. One of them is the Hello World program, which is the first program you write in any new environment. It simply pops up on the screen and says, Hello, World!. This is a fun tradition but also has a practical side. It is usually the simplest kind of activity you can make a computer do in a given language. By starting with such a simple program, you can focus your efforts on becoming comfortable with the programming environment. With a debugging and programming package as complex as Visual Studio, starting with a simple program so that you can get your feet wet in the environment makes a lot of sense.

The Hello World program featured in Figure 1.7 doesn’t do much, but it illustrates several important ideas in programming. When you understand the code behind this very simple program, you will have a framework that can be reused for every C# program you write.

Figure 1.7. As advertised, the program says “Hello, World!”


Getting into the Visual Studio .Net Environment

Although writing C# programs using any text editor is possible, you will probably spend most of your time using the Visual Studio Integrated Debugging Environment (IDE). The Visual Studio IDE is based on earlier Microsoft languages, notably Visual Basic and Visual C++. One interesting feature of the .NET version of the IDE is that the same environment is used to program many languages. This is consistent with the tighter integration that now exists between the Microsoft languages. Now there are fewer differences between programs written in different languages in the Microsoft universe.

After Visual Studio .NET (sometimes referred to as Visual Studio 7) is loaded onto your machine, you activate it as you would any other program–from the Start menu.

As you can see from Figure 1.8, the IDE is a very complicated beast. Don’t worry about understanding the whole thing at once. I’ll show you the various parts as you need them. For now, rely on your experience as a software user. It’s reasonable to guess that the icons represent the most commonly needed functions in the program and that all the major commands are available through the online menu system. You might want to hover your mouse over the screen icons to find the important ones (such as the New Project button). For the most part, you write programs in the large gray area in the center of the screen. Everything else on the screen gives you information about what’s going on in the program or gives you access to tools such as the command line and various windows components. Because you aren’t going to use those features yet, you can leave them alone for now.

Figure 1.8. The Visual Studio IDE as it appears on my computer.


Starting a New Project

Start a new project by clicking–you guessed it–the New Project button, which lives in the upper-left corner of the screen. If you are averse to buttons, you can choose New, Project from the File menu. In either case, you see a dialog box that looks like Figure1.9.

The New Project dialog box in Figure 1.9 has many important features. For example, the Project Types list box on the left enables you to determine which programming language you want to use. Depending on the way Visual Studio is configured on your system, you might have several other options. I currently have my machine configured for Visual Basic and C#. (I use other languages, too, but not usually in the .NET framework. Somehow it seems rude to use a Microsoft environment to write Perl code.) For the programs in this book, you always choose the C# environment.

Figure 1.9. The New Project dialog box is where you determine the programming language, the project’s name, and the type of project you are writing. Play button


Choosing the Project Type

After selecting the programming language, you can choose the type of project. You can use C# to write many types of programs. In the early stages of this book, you will write console applications, which are a simple interface because they are the easiest to understand. After you learn the basics of C# with these simple interfaces, you will graduate to Windows applications and eventually Web applications. For now, choose Console Application. However, be sure that you name your application and choose a location for it before pressing Enter or double-clicking the Console Application icon.

If you double-click the Console Application icon before choosing a name or location for your project, Visual Studio assigns you a default name and location. It can be a real pain to fix this after the fact, so be sure that you type in a name and location before pressing Enter or clicking OK. I’ve made this mistake a number of times.

Examining the Code Window

After you determine the general characteristics of the program, the IDE starts writing code for you. All programs of a certain type share certain characteristics, so Visual Studio will supply boilerplate code to get you started. You can think of the automatically generated code as an outline that you can flesh out to write your program.

Figure 1.10 displays the code window as it appears after a new project named HelloWorld is created. All the critical parts of any C# program are present, and the program will run, although it doesn’t do anything interesting yet.

Figure 1.10. The HelloWorld program displayed in the code window.


You have to learn a few things about C# before you start studying the code. Although Figure 1.10 doesn’t show it, the code is displayed in several colors. Words appear in blue, black, green, and gray. The colors indicate the type of information the compiler thinks each word is. For example, comments are in gray.

Also, you will note a certain symmetry to the text. Towards the beginning of the code are several left braces ({). Later in the code, you see matching right braces (}). The braces are used to group lines together. (I promise to show you exactly how. For now, I just want you to see the gestalt of the language so that you will understand later how the details fit together.) The braces are carefully matched so that every left brace has a right brace aligned directly underneath it (although sometimes several lines below the left brace) and everything inside the braces is indented. This is a common way of writing code in the languages derived from C, and because the IDE automates this style of code, you will stick with it now.

A passionate discussion about vertically aligning your braces is ongoing in programming circles. To tell the truth, most languages (including C#) completely ignore the spacing and indentation in your code. The spaces help the programmer, not the computer. I prefer a different indentation convention, but because this form is built-in to the editor and is a reasonably standard approach, I will go with it for this book. The most important thing is to have a consistent style and stick with it. As you will see, indentation, commenting, and the like, can have a major effect on how well you get your programs to work.

You will also see minus signs to the left of the editor. When you click one of these symbols, you “collapse” the braces that follow the indicated line. This helps you to look at specific parts of your program and hide unnecessary details.

Examining the Default Code

As I just mentioned, the IDE starts to build your code for you. For your part, you will begin by examining the boilerplate code and later will add a little functionality. Here’s code that Visual Studio created:

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 code is the same for any console-style application you write. Visual Studio gives you a starting place so that you don’t have to begin with a completely blank page. If you choose a different kind of application (like the Windows applications you will write later in this book) the IDE will generate.

Adding a Reference to a Namespace

The first line given by the IDE says using System. The using statement indicates that a program will be using commands from a specific namespace. In a sense, the idea of namespaces is already familiar to you. At home, my wife calls me Andy. Calling me Andy Harris would be silly because everybody in our house is named Harris. At my job, there’s another guy named Andy, so people are more likely to say Andy Harris when they want to talk to me. You can always use a first name and a last name, but at home, your last name is implied.

Referring to a Namespace with a Using Statement

The using statement in C# works in a similar way. It enables you to use a group of commands that are related. You will see many namespaces in future chapters, but almost every program written in C# uses the System namespace because it contains useful objects. You need the console later, and the console object’s full name is System.Console. If you use the using System statement at the beginning of your program, you can simply refer to Console instead of System.Console. Almost every program in C# starts with the using System statement. As you learn more about C#, you will learn about other namespaces you will want to include in your programs.

Creating a Custom Namespace

The namespace HelloWorld line is used to generate your own namespace. In addition to the namespaces built in to the .NET environment, each project you create can have its own namespace. By default, the editor builds a namespace based on the project’s name. The namespace is called HelloWorld but actually contains all the code on the screen. You can see the left brace immediately after the namespace line. All the code is then indented until the corresponding right brace. This indentation scheme helps you remember that all the interior code is part of the namespace.

Adding Summary Comments

Right after the namespace definition, you see three lines that begin with three slashes (///). Lines that begin this way are used to create documentation for your programs. Generally, you leave alone the lines containing <summary> and </summary>and, between these lines, add text that describes your project. This description of your program is stored along with your program. One advantage of C# is that programs are supposed to have some of the documentation built in. Any comments you put between the summary tags will be part of this automatic documentation. Of course, if you don’t add comments, the automatic documentation feature cannot work.

Creating the Class

Class1 defines a class. Essentially, a class is a way of grouping your code. For now you can think of a program as a class because your early programs will have one namespace and one class. As you get more sophisticated, you’ll build namespaces with multiple classes. Classes are the key to C# programming. Right now, the HelloWorld namespace has one class in it, Class1. Actually, the official name of the class is HelloWorld.Class1, but because you are inside the HelloWorld namespace, you don’t have to worry about specifying the namespace. Generally, one of the first things you do when creating a program is rename your class. As a programmer, you get many opportunities to name things. Give your class a name that describes what the program does. Later in this chapter, you will change the class name from Class1 to Hello. Class names in C# usually start with a capital letter.

Like the namespace, a class definition begins a new part of the code and has a pair of braces to denote the new structure.

Whenever you create a new program, be sure to change the name of the class. Although the program will run without changing the name, you will find this confusing later, especially when your programs have a number of classes.

Examining the Main() Method

static void Main(string[] args) begins the Main() method. Any code inside this pair of braces automatically executes when the program is run. For now, all the code in your programs will go inside the Main() method.

Watch your capitalization, especially if you’re accustomed to other C languages. C# uses a capital M in Main, but most other variants of C use a lowercase m.

I will explain later what all the parts of the Main command are, so don’t be intimidated by the string[] args). For now, you don’t need to worry about these details because the editor will build this line for you. You can concentrate, instead, on customizing this code to make it do something interesting.

Examining the Rest of the Code

Inside the Main() method, you see three lines that begin with two slashes (//). Any line that begins with these slashes is a comment. The compiler ignores comments. However, comments are among the most important aspects of good programming. You use comments to document your code–to explain something that’s going on or to make a note to yourself. The comments here tell you where you will write the actual code. You will delete these comment lines and replace them with program code.

You also see a series of right braces. Each of these right braces is vertically aligned with its corresponding left brace. If you don’t include all the right (closing) braces, your program will not work correctly.

Modifying the Code

Although the IDE creates all this code for you, the first part of writing a C# program is to make changes to the code you’re given. You have to make a number of changes right away. Take a look at my modified version of the code:

using System;

namespace HelloWorld
{ 
       /// <summary>
       /// The classic first program in C#
       /// Andy Harris, 10/01
       /// </summary>
       class Hello
       {
              static void Main(string[] args)
              {
                     //
                     // TODO: Add code to start application here
                     //
              } // end main
        } //end class
  } // end namespace

I made a number of small but important changes to the program. First, I added comments to the summary section. At a minimum, you should add comments (to remind yourself what the program is supposed to do), your name, and the date. This might seem like a silly exercise, but it’s a very good habit to form. Note that these summary comments begin with three slashes.

Next, I changed the name of the class from Class1 to Hello. Hello is a much better name for the class because it is more descriptive than Class1.

For the time being, I left the content of the Main() method (the comments with the TODO note in them) alone. I’ll change those soon, but first, there’s some more housekeeping to do.

You might want to add comments after every right (closing) brace because you will have many of these braces in your C# travels, and it’s easy to get confused. Because you use the same character to end a namespace, method, and class definition, figuring out exactly what you intended to end can be a challenge. Not every programmer does this, but I think that it’s a terrific habit to cultivate, especially when you’re getting started.

Writing to the Console

At this point, your program still doesn’t do what it’s supposed to do–greet the user. Now you are ready to change the code in the Main() method. Take out those comment lines and add the following line of code:

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

This line of code sends the message Hello World to the console, which is another way of saying to the DOS prompt. (Remember, you are beginning with DOS-based programs because they are simpler, but you will graduate to Windows-style programs soon enough.)

On the next line, write the following code:

Console.ReadLine();

This line causes the program to stop and wait until the user presses Enter. If you don’t add this line (or something like it), the program will stop running and disappear before the user can read the greeting.

As soon as you type the period after Console, a list of possible completions appears in the editor window. You can use the arrow keys to look at the entire list and the Tab key to choose the selected element. Because the Console is part of the System namespace, the editor knows all the terms that can be associated with it and gives you an easy way to choose legal terms to finish the statement. When you write the left parenthesis, you see a similar little window explaining which kind of data should go in the parentheses. These little helper windows prevent mistakes by giving you hints on the syntax of C#.

Placing Semicolons Correctly

As you look at the code, you see a semicolon (;) at the end of some lines but not others. You can spot one at the end of the using line and the Console lines but not in the other lines in the program. A pair of braces follows most of the other lines in the program. These indicate that the line begins a structure, such as a namespace, class, or function. The set of braces and whatever they contain are considered a part of that line. Many of the other commands (such as the two I mentioned at the beginning of this paragraph) do not begin a structure. To tell the compiler that you are finished writing a particular command, you must end the line with a semicolon (like writing a period at the end of a sentence to indicate that the sentence is finished).

Most of the time, a semicolon appears at the end of a line of C# code. The only time this is not true is when

  • The next character is a left brace.

  • The current character is a right brace.

  • You are writing one logical line of code on more than one line on the text editor.

Don’t get hung up on memorizing these rules. After you write a few programs, placing semicolons will be a snap.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.123.155