O'Reilly logo

Learning C# 2005, 2nd Edition by Brian MacDonald, Jesse Liberty

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 will be discussed in coming chapters, including classes, namespaces , statements, static methods, objects, strings, blocks, and libraries.

It is as if 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 line in the program defines a namespace:

namespace NotePad

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 saying “These names are mine.”

In this program, you’ve created a namespace called NotePad. 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 NotePad namespace. The open brace is matched by a closing brace at the end of the program.

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. A class is a new, user-defined type. 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, etc.), 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 6 and 7.

Every class named within the namespace braces is implicitly prefixed with the name NotePad. The dot operator (.) separates the namespace from the name of the class within the namespace. Thus, if you were to create a class MyClass within the namespace NotePad, the real name of that class would be NotePad.MyClass. You can read this as either “NotePad dot MyClass” or “NotePad MyClass.” Actually, 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, aptly, HelloWorld. Like a namespace, a class is defined within braces. The following code represents the opening of the HelloWorld class definition:

    class HelloWorld
    {

A method is a relatively small block of code that performs an action. The Main( ) method is the “entry point” for every C# console application; it is where your program begins. The next few lines in Hello World mark the beginning of the Main( ) method:

    static void Main(  )
    {

Methods are covered in detail in Chapter 8, but are mentioned in virtually every chapter in this book.

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

// every console app starts with Main
    static void 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.

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. XML comments are beyond the scope of this book.

Tip

You will note that I use few comments in the examples in this book. Even so, I tend to use more comments in a book than I do in professional code. It’s not that I don’t believe in fully documenting code; it’s just that I may disagree with others about what “fully documented” means. My personal set of guidelines is this:

  • Prefer self-documenting code to comments (see http://en.wikipedia.org/wiki/Self-documenting).

  • Use comments when you need to explain why you did it, not what you did.

  • Comments that say what the code is doing are a sign that the code may not be written well—it should be obvious what the code is doing, and if not, the code will be hard to maintain.

  • Remember that comments rust. The code changes, and inevitably the comments are not fully updated.

  • Comments that mislead are far worse than no comments at all.

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

static void Main(  )

The static keyword indicates that you can access this method without having an object of your class available. While 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 is an individual instance of Car). Thus, while Button defines a type of control for a Windows program, any individual program will have many Button objects, each with its own label (e.g., OK, Cancel, Retry).

Normally, methods can be called only if you have an object, but static methods are special and are called without an object. (The use of static methods, other than Main( ), is fairly advanced and won’t be covered until Chapter 7.)

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

    staticvoid Main(  )

Typically, one method calls another. The called method will do work, and it can return a value to the calling method. (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, you’ve declared that Main( ) will not return a value.

Every method name is followed by parentheses:

    static void Main(  )

It is possible to pass values into a method so that the method can manipulate or use those values. These values are called parameters or arguments . (Method parameters are covered in Chapter 8.) In this case, Main( ) has no parameters.

All methods are 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 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 string you want to display. 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, you can save typing by telling the compiler that many of the objects you’ll refer to are in that namespace. You do so by adding a using directive to the beginning of your program:

    using System;

Once you add this line, you can use the Console class name without explicitly identifying that it is in the System namespace. If you add 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 open 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 you’ve closed the class. Similarly, the method Main( ) is declared within the class, so you do not close the class until you’ve closed the method.

Whew! That was a lot to take in all at once! Don’t panic; all the concepts introduced here are explained in detail in coming chapters. Oh, and that’s the last time you’ll use Notepad to write a program (if you know what is good for you!). From now on, we’ll use Visual Studio 2005 (or Visual C# 2005 Express).

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required