Examining Your First Program

The single greatest challenge when learning to program is that you must learn everything before you can learn anything. Even this simple Hello World program uses many features of the language that we will discuss in coming chapters, including classes, namespaces, statements, static methods, objects, strings, blocks, and libraries.

It’s as though you were learning to drive a car. You must learn to steer, accelerate, brake, and understand the flow of traffic. Right now, we’re going to get you out on the highway and just let you steer for a while. Over time, you’ll learn how to speed up and slow down. Along the way, you’ll learn to set the radio and adjust the heat so that you’ll be more comfortable. In no time you’ll be driving, and then won’t your parents begin to worry.

Hang on tight; we’re going to zip through this quickly and come back to the details in subsequent chapters.

The first four lines in the program are called using statements:

using System;
using System.Collections.Generic;

using System.Linq;
using System.Text;

Visual Studio inserted these for you automatically. These using statements provide a shorthand way to access various parts of the .NET Framework that you might want to use in your program. In fact, you used only the first one this time around, but it doesn’t hurt anything to have the others there. We’ll discuss the System part in just a minute.

The next line in the program defines a namespace:

namespace HelloWorld
{

You will create many names when programming in C#. Every object and every type of object must be named. It is possible for the names you assign to conflict with the names assigned by Microsoft or other vendors. A namespace is a way of distinguishing your names from anybody else’s.

In this program, you’ve created a namespace called HelloWorld. Visual Studio assigned this namespace for you automatically because that was the name you gave your project. The items defined in your namespace must be enclosed in braces ({}). Thus, the second line of the Hello World program is an open brace to mark the beginning of the HelloWorld namespace. The open brace is matched by a closing brace at the end of the program. Get used to seeing these braces—you’ll use them a lot in C#, usually with braces nested inside braces. Forgetting to include a closing brace is a common syntax mistake. Some programmers like to type the closing brace immediately after the opening one, but on a new line, and then go back and fill in the code between the braces.

Within the braces of the namespace, you write other programming constructs. For instance, you might define a class. Classes define a category, or type, of object. The .NET Framework provides thousands of classes, and you can define new ones of your own as well. Classes are used to define the attributes and behavior of Windows controls (buttons, listboxes, and so on), as well as constructs that mimic the important attributes or behavior of things in the world, such as employees, students, telephones, and so on.

Classes are the core of C# and object-oriented programming. You’ll learn about classes in detail in Chapters Chapter 6 and Chapter 7.

Every class named within the namespace braces is implicitly prefixed with the name HelloWorld. The dot operator (.) separates the namespace from the name of the class within the namespace. Thus, if you were to create the class MyClass within the namespace HelloWorld, the real name of that class would be HelloWorld.MyClass. You can read this as either “HelloWorld dot MyClass” or “HelloWorld MyClass.” Like the braces, you use the dot operator quite a lot; you’ll see various other uses as we proceed.

The third line in our Hello World program creates a class named Program. Again, this is the default name for the class, which Visual Studio provided for you. Like a namespace, a class is defined within braces. The following code represents the opening of the Program class definition:

class Program
{

A method is a relatively small block of code that performs an action. Methods are always contained within classes. The Main() method is a special method in C#—it’s the “entry point” for every C# application; it is where your program begins. The next few lines in Hello World mark the beginning of the Main() method:

static void Main(string[] args)
{

We cover methods in detail in Chapter 8, but we mention them in virtually every chapter in this book.

A comment (shown here in bold) appears just after the start of the Main() method:

static void Main(string[] args)
{
   // every console app starts with Main

A comment is just a note to yourself. You insert comments to make the code more readable to yourself and other programmers. You’ll be surprised how helpful those comments are six months later when you have no idea what a line of code you wrote actually does.

You can place comments anywhere in your program that you think the explanation will be helpful; they have no effect on the running program. The compiler knows to ignore them.

C# recognizes three styles of comments. The comment in Hello World begins with two slashes (//). The slashes indicate that everything to the right on the same line is a comment.

The second style is to begin your comment with a forward slash followed by an asterisk (/*) and to end your comment with the opposite pattern (*/). These pairs of characters are called the opening C-style comment and the closing C-style comment, respectively.

Tip

These comment symbols were inherited from the C language—thus the names used to identify them. They are also used in C++ and Java.

Everything between these comment symbols is a comment. C-style comments can span more than one line, as in the following:

/* This begins a comment
This line is still within the comment
Here comes the end of the comment */

The third and final style of comments uses three forward slashes (///). This is an XML-style comment and is used for advanced documentation techniques, so we won’t discuss it in this book.

Tip

You will note that we don’t use many comments in the examples in this book. Most of that is for space reasons; we’d rather explain what the code does in the text than clutter the pages with comments.

Notice that the Main() method is defined with the keywords static and void:

static void Main(string[] args)

The static keyword indicates that you can access this method without having an object of your class available. Whereas a class defines a type, each instance of that type is an object (much as Car defines a type of vehicle and your aging rust-bucket or shiny roadster is an individual instance of Car). Thus, whereas Button defines a type of control for a Windows program, any individual program will have many Button objects, each with its own label (such as OK, Cancel, or Retry).

Normally, methods can be called only if you have an object, but static methods are special and are called without an object. (We’ll cover the use of static methods, other than Main(), in Chapter 7.)

The second keyword in the statement defining the Main() method is void:

static void Main(string[] args)

Typically, one method calls, or invokes, another method. The called method will do the work, and it can return a value to the method that called it. (You’ll see how methods call one another and return values in Chapter 8.) If a method does not return a value, it is declared void. The keyword void is a signal to the compiler that your method will not return a value to the calling method.

The operating system calls Main() when the program is invoked. It is possible for Main() to return a value (typically an error code) that might be used by the operating system. In this case, though, you’ve declared that Main() will not return a value.

Every method name is followed by parentheses:

static void Main(string[] args)

When you create your own method, you may want it to use data from elsewhere in your application. To do that, you pass values into your method so that the method can manipulate or use those values. These values are called parameters or arguments. (We cover method parameters in Chapter 8.) When you pass in values, those values are contained inside the parentheses. In this case, Main() has a single parameter: string[] args. Don’t worry about that for now; that’s another bit of code Visual Studio inserted for you, but it doesn’t make a difference in this program. You can delete that parameter, and your program will still run the same. Don’t delete the parentheses, though; all method calls must be followed by the parentheses, even if the parentheses are empty.

The body of the method is always enclosed within braces. Within the braces for Main() is a single line of code:

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

The Console is an object that represents the window on your screen. The Console class is defined within the System namespace, and so its full identification is System.Console.

The Console class has a static method, WriteLine(), which you access not with an instance of Console, but through the Console class itself. Because you access the method with the dot operator, you write System.Console.WriteLine.

The WriteLine() method declares a single parameter: the text you want to display. In C#, a set of characters is referred to as a string. You’ll learn a lot more about strings in Chapter 15, but for now, just know that a string is a block of text in quotes. When you pass a string in to the method, the string is an argument. The argument ("Hello World") corresponds to the parameter the method expects, and the string is displayed. The complete call to the method is:

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

If you will use many objects from the System namespace (and you will), you can save typing by telling the compiler that many of the objects you’ll refer to are in that namespace. That’s what the using directive is for at the beginning of your program:

using System;

With this line in place, you can use the Console class name without explicitly identifying that it is in the System namespace. With the using declaration, you can rewrite the contents of Main() as follows:

Console.WriteLine("Hello World!");

The final series of lines close the various nested opening braces. The first closes the brace for Main(), the second closes the brace for the class, and the third closes the brace for the namespace. Each opening brace must be matched by a closing brace.

The class is defined within the namespace declaration, and thus you do not close the namespace until after you’ve closed the class. Similarly, the method Main() is declared within the class, so you do not close the class until after you’ve closed the method.

Whew! That was a lot to take in all at once! Don’t panic; in coming chapters, we’ll explain in detail all the concepts we introduced here.

Get Learning C# 3.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.