Partilhar via


C# and .NET Programming

This chapter is excerpted from Learning C# 3.0: Master the fundamentals of C# 3.0 by Jesse Liberty, Brian MacDonald, published by O'Reilly Media

Learning C# 3.0

Logo

Buy Now

Welcome to Learning C# 3.0. We're here to teach you the C# language from the ground up. If you've never done any programming before, in any language, start here in Chapter 1, C# and .NET Programming, and we'll have you writing real working applications in no time flat-before you reach the end of this chapter. If you have a little programming background in VB 6, PHP 4, or another non-object-oriented language, you'll find a lot in this book that's familiar, but also a lot that's new. You'll probably find the code in the first few chapters to be recognizable, but you may want to read the chapters anyway to get the hang of the syntax. Classes and objects are at the core of how C# works, though, so we'll get to those quickly, once we've covered the basics.

Tip

If you're a programmer migrating from Java or C++, you may find the material in Programming C# 3.0 by Jesse Liberty and Donald Xie (O'Reilly) a more appropriate fit for your skills.

To start at the very beginning, C# is a modern language created by Microsoft as part of its .NET platform of languages. .NET is a layer of software that makes it easier for you to write programs that can communicate with the operating system (in this case, Windows). As the name implies, C# has its roots in C++, but over three versions, it has evolved its own techniques and elements that make it distinct. Most important, C# has the backing of the .NET Framework behind it, which we'll get into shortly. We're not going to assume that you have any C++ experience, so we won't frame our discussions of C# in terms of C++, or any other programming language. What you need to know right now is that you can write applications in C# that will do just about anything you need to do. You can write applications to manage your company's inventory (interacting with a database); you can write applications to analyze documents; you can write games; you can create an entire operating system in C# if you have a mind to. The .NET Framework allows C# to operate seamlessly with Windows, and take advantage of the familiar Windows features that users all over the world already know. You can also create C# applications that you can use on the Web, in much the same way.

To be completely honest, most modern object-oriented languages are rather similar underneath. The choice of one over the other is usually just a matter of personal preference. C# and Visual Basic have the advantage of the .NET Framework, but third-party languages can interact with the framework, too. C#'s similarity to C++ and Java makes it easy to learn for programmers familiar with those languages, but it's also easy to learn as your first language. Once you have the basics of C# down, you'll find it much easier to learn any other language you want to.

Unless we specifically say otherwise, when we refer to C# in this book, we mean C# 3.0; when we refer to .NET, we mean the .NET 3.5 Framework; and when we refer to Visual Studio, we mean Visual Studio 2008. We could spend some time telling you about the cool new features of C# 3.0 over its predecessors-and we're pretty excited about them-but if you're new to the language, it's all new to you, so there's little point in calling attention to specific features.

Finally, when we refer to using Visual Studio 2008, you may be using Visual C# 2008 Express Edition instead. C# Express is the free version of Visual Studio, designed for students and home users, but that doesn't mean it's a toy. In fact, the examples in this book were written and tested using C# Express. C# Express has the same compiler and libraries as Visual Studio, and within the examples in this book, you won't find any significant differences. There are some small differences in look and feel, or in feature names, and any time those come up, we'll mention them.

Installing C# Express

Visual C# 2008 Express Edition has all the features you'll need for the examples in this book, and it has the additional advantage of being completely free from Microsoft. Getting C# Express is very simple-just go here:

https://www.microsoft.com/express/download/

Here, you'll find download links for each of the free Visual Studio 2008 Express Editions. Scroll down to the Visual C# box (it's the green one), select your language, and click the Download link. Save the installer to your hard drive, and then run it. Most of the installation is pretty standard, but there is one step you should pay attention to, shown in Figure 1.1, "During the C# Express installation, select the MSDN Library if you have the space and the SQL Server 2005 Express option if you want to work through the data examples in Chapters Chapter 20, ADO.NET and Relational Databases and Chapter 21, LINQ.": the installation options.

The MSDN Library contains useful help files, and if you have the space available, you should install it, but it's not strictly necessary for this book. The second option, Microsoft SQL Server 2005 Express Edition, allows you to access databases with your code. You won't need it for a while if you're reading this book straight through, but we do use it in Chapters Chapter 20, ADO.NET and Relational Databases and Chapter 21, LINQ, so you may want to install it now. (You can install it separately later, if you want.) The Silverlight runtime is an amazing new technology from Microsoft, but we won't be covering it in this book, so you can skip that.

Figure 1.1. During the C# Express installation, select the MSDN Library if you have the space and the SQL Server 2005 Express option if you want to work through the data examples in Chapters Chapter 20, ADO.NET and Relational Databases and Chapter 21, LINQ.

During the C# Express installation, select the MSDN Library if you have the space and the SQL Server 2005 Express option if you want to work through the data examples in Chapters and .

The rest of the installation is mostly automatic. When you're done, you'll find a link in your Start menu, ready to go.

We'll give you a full tour of Visual Studio and C# Express in the next chapter. For this chapter, we'll tell you exactly what to do and when. Right now, we'll look a little more closely into the .NET platform to get you started, and then it'll be time to write some code.

C# 3.0 and .NET 3.5

In the past, you might have learned a language such as C or Java without much concern about the platform on which you would be programming. These languages had versions available for various operating systems, whether that was a Unix box or a PC running Windows.

C#, however, was created specifically for .NET. Although cross-platform versions of .NET do exist, for now the overwhelming majority of .NET programs will be written to run on a machine running one of the Windows operating systems.

The .NET Platform

When Microsoft announced C# 1.0 in July 2000, its unveiling was part of a much larger event: the announcement of the .NET platform. The .NET platform is a development framework that provides a new way to create Windows applications. However, .NET goes beyond traditional Windows programming to facilitate creating web applications quickly and easily.

Microsoft reportedly devoted 80% of its research and development budget to .NET and its associated technologies. The results of this commitment were very impressive. In 2005, Microsoft rolled out version 2 of the language, the platform, and the tools. Its goal was to radically reduce the amount of boilerplate code you have to write, and to make the creation of web and desktop applications easier by "encapsulating" much of the "plumbing" of a typical application into objects. That means that rather than writing a lot of the code to connect to databases, the Internet, or your filesystem, .NET provides fully tested objects that will do all the heavy lifting for you.

In 2007, .NET version 3.0 brought .NET up-to-date with Microsoft's new Vista and Windows Server 2008 operating systems. The most visible change in this version of the framework was to provide support for the Windows Presentation Foundation (WPF), which opens up new graphics possibilities, such as those you'll find in Windows Vista, as you'll see later in this book. And now, with the release of Visual Studio 2008, .NET version 3.5 supports more new features, including LINQ, a new feature that allows you to query databases with a more natural, object-oriented syntax.

The scope of .NET is huge. The platform consists of three separate product groups:

  • A set of languages, including C# and Visual Basic .NET; a set of development tools, including Visual Studio 2008; and powerful tools for building applications, including the Common Language Runtime (CLR), a platform for compiling, debugging, and executing .NET applications

  • A set of Enterprise Servers, including SQL Server 2008, Exchange, BizTalk, and so on, that provide specialized functionality for relational data storage, email, business-to-business (B2B) commerce, and so forth

  • .NET-enabled non-PC devices, from cell phones to game boxes

The .NET Framework

Central to the .NET platform is a development environment known as the .NET Framework. The framework provides a lot of features, but for now all you need to know is that the C# language provides you with the elements that allow you to access the framework to make your programs work. You will learn about these elements in the chapters ahead.

The .NET Framework sits on top of any flavor of the Windows operating system. The most important components of the framework are the CLR, which is what allows you to compile and execute applications, and the Framework Class Library (FCL), which provides an enormous number of predefined types or classes for you to use in your programs. You will learn how to define your own classes in Chapter 7, Classes and Objects.

Tip

Detailed coverage of all the FCL classes is beyond the scope of this book. For more information, see C# 3.0 in a Nutshell by Joseph Albahari and Ben Albahari (O'Reilly), and the MSDN Library (https://msdn.microsoft.com/library).

The C# Language

The C# language is disarmingly simple, which makes it good for beginners, but C# also includes all the support for the structured, component-based, object-oriented programming that one expects of a modern language built on the shoulders of C++ and Java. In other words, it's a fully featured language appropriate for developing large-scale applications, but at the same time it is designed to be easy to learn.

A small team led by two distinguished Microsoft engineers, Anders Hejlsberg and Scott Wiltamuth, developed the original C# language. Hejlsberg is also known for creating Turbo Pascal, a popular language for PC programming, and for leading the team that designed Borland Delphi, one of the first successful integrated development environments (IDEs) for client/server programming.

The goal of C# is to provide a simple, safe, object-oriented, high-performance language for .NET development. C# is simple because there are relatively few keywords. Keywords are special words reserved by the language that have a specific meaning within all C# programs, including if, while, and for. You'll learn about these keywords in the coming chapters.

C# is considered safe because the language is type-safe, which is an important mechanism to help you find bugs early in the development process, as you'll see later. This makes for code that is easier to maintain and programs that are more reliable.

C# was designed, from the very start, to support object-oriented programming. In this book, we'll explain not only how to write object-oriented programs, but also why object-oriented programming has become so popular. The short answer is this: programs are becoming increasingly complex, and object-oriented programming techniques help you manage that complexity.

C# was designed for .NET, and .NET was designed (in part) for developing web and web-aware programs. The Internet is a primary resource in most .NET applications.

Your First Program: Hello World

At the most fundamental level, a C# application consists of source code. Source code is human-readable text written in a text editor. A text editor is like a word processor, but it puts no special characters into the file to support formatting, only the text. You could use any old text editor to write your code, but since you'll be using Visual Studio throughout this book, that's the best choice. Start up C# Express or Visual Studio. The first thing you'll see is the Start Page, which will look similar to Figure 1.2, "The Start Page for Visual C# 2008 Express. It looks pretty empty now, but that won't last long. You'll be using the Create link on the lefthand side.".

Figure 1.2. The Start Page for Visual C# 2008 Express. It looks pretty empty now, but that won't last long. You'll be using the Create link on the lefthand side.

The Start Page for Visual C# 2008 Express. It looks pretty empty now, but that won't last long. You'll be using the Create link on the lefthand side.

There's a lot of news in the middle, which you don't need to pay attention to right now. We'll give you a full tour of the Visual Studio interface in Chapter 2, Visual Studio 2008 and C# Express 2008, but for now you need the Recent Projects box on the left. If you just installed Visual Studio, that box is empty at the moment, because you haven't created any projects yet. That's about to change. Click Project, next to the Create link. The New Project dialog box opens, as you can see in Figure 1.3, "This is where you'll create all your Visual Studio projects. There are a lot of template options here, but for now just select Console Application and type HelloWorld in the Name field.".

There are lots of options here that we'll discuss later, but for now we just want to get you started. Select Console Application from the row of templates at the top. When you do that, the content of the Name field at the bottom will change to ConsoleApplication1, which is a fine name, but not very descriptive. Change it to HelloWorld (without a space) and then click OK.

Figure 1.3. This is where you'll create all your Visual Studio projects. There are a lot of template options here, but for now just select Console Application and type HelloWorld in the Name field.

This is where you'll create all your Visual Studio projects. There are a lot of template options here, but for now just select Console Application and type HelloWorld in the Name field.

Visual Studio creates the project for you, along with the necessary files. Again, you don't need to know about most of this yet, but it's nice that Visual Studio does it for you. It also creates the program where you'll write your code, called Program.cs. Finally, Visual Studio opens Program.cs in an editing window for you to work on. Visual Studio provides some basic code that's common to all C# console programs, called a skeleton, which saves you even more time. Your Visual Studio screen should now look like Figure 1.4, "Visual Studio does all the work of setting up your application automatically, which saves a lot of time. It even creates this program skeleton for you, ready for you to add your own code.".

In this first example, you will create a very simple application that does nothing more than display the words Hello World to your monitor. This console application is the traditional first program for learning any new language, and it demonstrates some of the basic elements of a C# program.

After you write your Hello World program and compile it, we'll provide a line-by-line analysis of the source code. This analysis will give you a brief preview of the language; we'll describe the fundamentals much more fully in Chapter 3, C# Language Fundamentals.

As we mentioned, the skeleton of the program is already there for you, but you still need to write a little code. The editing window you're looking at now works much like any word processing program you're familiar with, or even like Windows Notepad. However, you'll find that Visual Studio has a lot of helpful features for writing code that those other applications lack. Right now, click after the open brace ({) underneath static void Main. Press Enter once to open up some space (notice that Visual Studio indents for you automatically-this is a good thing), and then type the following:

Figure 1.4. Visual Studio does all the work of setting up your application automatically, which saves a lot of time. It even creates this program skeleton for you, ready for you to add your own code.

Visual Studio does all the work of setting up your application automatically, which saves a lot of time. It even creates this program skeleton for you, ready for you to add your own code.

// every console app starts with Main
System.Console.WriteLine("Hello World!");

As you type, you'll notice that Visual Studio automatically colors your code, and that it'll open small windows (called IntelliSense windows) suggesting code that you might want to include. Don't worry about any of that for now; just type the code as shown here.

Example 1.1, "A simple source code file; this application doesn't look like much, but it's a fully functional application that you'll run in just a moment" shows the code that you should see in your editing window right now. The lines that you added are shown here in bold. Be sure to pay attention to the capitalization, especially capitals where you wouldn't normally expect them, as in WriteLine. C# is case-sensitive, and if you lowercase the L here, you'll get an error message (and not necessarily a helpful error message).

Example 1.1. A simple source code file; this application doesn't look like much, but it's a fully functional application that you'll run in just a moment

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HelloWorld
{
   class Program
   {
      static void Main(string[] args)
      {
         // every console app starts with Main
         System.Console.WriteLine("Hello World!");
      }
   }
}

You should save your code before you go any further. Click the Save All button () on the toolbar. You'll see a dialog box asking you where you want to save your work; the My Documents/Visual Studio 2008/Projects folder is the default, but you can save your work wherever you like. Each project you create will have its own subfolder.

We'll explain this program detail in a bit. For now, just look at the language-the program is readable; it is in normal text. The words may be strange and the layout unusual, but there are no special characters-just the normal text produced by your keyboard.

The source code makes up a set of instructions for the application to follow. The syntax for these instructions is strictly defined by the language. In C#, source code consists of a series of statements. A statement is an instruction to the compiler. Each instruction must be formed correctly, and one task you'll face when learning C# will be to learn the correct syntax of the language. For example, in C#, every statement ends with a semicolon.

Each instruction has a semantic meaning that expresses what you are trying to accomplish. Although you must follow the rules of C# syntax, the semantics of the language are far more important in developing effective object-oriented programs. This book will provide insight into both the syntax and the semantics of good C# programs.

We know you'll want to run your new program right away, but bear with us for just a moment while we explain just what Visual Studio has to do to make that happen.

The Compiler

After you write your program in an editor and save it to disk, you must compile it. Compiling is the process of turning the code that you can read into code that the machine can read. For that, you need a compiler. Then, once you've compiled the program, you need to run and test it.

The job of the compiler is to turn your source code into a working program. It turns out to be just slightly more complicated than that because .NET uses an intermediate language called Microsoft Intermediate Language (MSIL, sometimes abbreviated as IL). The compiler reads your source code and produces MSIL. When you run the program, the .NET Just In Time (JIT) compiler reads your MSIL code and produces an executable application in memory. You won't see any of this happen, but it's a good idea to know what's going on behind the scenes.

Tip

The MSIL code is actually stored in an .exe file, but this file does not contain executable code. It contains the information needed by the JIT to execute the code when you run it.

Visual Studio provides a built-in compiler that you'll use pretty much all the time. To compile and run Hello World, select Debug → Start Without Debugging, and your program executes, as shown in Figure 1.5, "These are the results you'll see in the command window after you've compiled and run Hello World.". You can also press Ctrl-F5 to do the same thing. You may notice a button on the toolbar () that will also compile and run your program, but you don't want to use that this time. If you do (and feel free to try this), your program will still execute, but the console window will close immediately, before you have a chance to see what you've done. Start Without Debugging opens the window, but adds the line "Press any key to continue … " after your program's output. Go ahead and press a key now to dismiss the window and end the program.

Presto! You are a C# programmer. That's it, close the book, you've done it. OK, don't close the book-there are details to examine, but take a moment to congratulate yourself. Have a cookie.

Granted, the program you created is one of the simplest C# programs imaginable, but it is a complete C# program, and it can be used to examine many of the elements common to C# programs.

If your program didn't run as anticipated, don't panic. If something is wrong in the code, Visual Studio will pop up a dialog box saying "There were build errors. Would you like to continue and run the last successful build?" In a program this simple, you most likely made what's called a syntax error, which is a term programmers use because they don't want to admit they made a typo, which is usually what happened. Select No in this dialog and Visual Studio will open an error window at the bottom of the interface with a message that may or may not be helpful, depending on exactly what's wrong.

Figure 1.5. These are the results you'll see in the command window after you've compiled and run Hello World.

These are the results you'll see in the command window after you've compiled and run Hello World.

Go back and check your code very carefully, and make sure it matches the code in Example 1.1, "A simple source code file; this application doesn't look like much, but it's a fully functional application that you'll run in just a moment" exactly. Make sure there's a semicolon at the end of the line containing the WriteLine, and that you've capitalized correctly. Make sure you have open and close quotation marks around "Hello World" and make sure you have open and close parentheses around the quotes. Make sure the first line you added starts with two forward slashes (//); the entire line should appear in green, if you've done it correctly. Make any necessary fixes, and then try to build and run the program again.

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, Object-Oriented Programming and Chapter 7, Classes and Objects.

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, Inside Methods, 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, Classes and Objects.)

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, Inside Methods.) 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, Inside Methods.) 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, Strings, 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.

The Integrated Development Environment

Although you can perform all of these writing and compiling tasks using Notepad and various command-line tools, your programming life will be much easier if you use the integrated development environment (IDE) called Visual Studio 2008. Visual Studio 2008 was designed with .NET development in mind, and it greatly simplifies the writing of C# program code. This book assumes you are using Visual C# 2008 Express or Visual Studio 2008, both of which provide the Visual Studio 2008 development environment.

Tip

The overwhelming majority of C# programmers will be building Windows and web applications for the .NET platform using Visual Studio 2008 or Visual C# 2008 Express, and we've tested all the examples for this book in that environment. Excellent open source C# compilers are available, such as those from the Mono project (https://www.mono-project.com) and #develop (http://www.icsharpcode.net/OpenSource/SD/). Everything in this book should work with those compilers, but we have not tested with them and cannot guarantee 100% compatibility.

The Visual Studio 2008 IDE provides enormous advantages to the C# programmer. This book tacitly assumes that you'll use Visual Studio 2008 or Visual C# 2008 Express for your work. However, the discussion focuses more on the language and the platform than on the tools.

Nonetheless, Chapter 2, Visual Studio 2008 and C# Express 2008 provides an introduction to the IDE in some detail. Chapter 9, Basic Debugging returns to the IDE to examine the debugger, which will help you find and correct problems in your code.

You can use the C# language to develop four types of applications:

  • Console applications
    A console application runs in a console window, as you saw with Hello World. A console window (or DOS box) provides simple text-based output. Console applications are very helpful when you're learning a language because they strip away the distraction of the Windows graphical user interface (GUI). Rather than spending your time creating complex windowing applications, you can focus on the details of the language constructs, such as how you create classes and methods, how you branch based on runtime conditions, and how you loop. We will cover all of these topics in detail in later chapters.

  • Windows applications
    A Windows application runs on a PC's desktop. You are already familiar with Windows applications such as Microsoft Word and Excel. Windows applications are much more complex than console applications and can take advantage of the full suite of menus, controls, and other widgets you've come to expect in a modern desktop application. In this book, you'll learn how to create Windows Forms applications in Chapter 18, Creating Windows Applications, and the fancier WPF applications in Chapter 19, Windows Presentation Foundation.

  • ASP.NET applications
    An ASP.NET application runs on a web server and delivers its functionality through a browser such as Internet Explorer or Firefox, typically over the Web. ASP.NET technology facilitates developing web applications quickly and easily. You'll learn more about ASP.NET applications in Chapter 18, Creating Windows Applications.

    Tip

    For an introduction to ASP.NET, see Learning ASP.NET 3.5 by Jesse Liberty et al. (O'Reilly).

  • Web services
    Web services are complex applications that can be accessed using standard Internet protocols, and that can provide services such as current stock quotes, ISBN-to-title conversions, and so forth that other applications can use. Web services are an advanced topic, and we won't cover them in this book.

This book will focus primarily on the basics of the C# language, using simple console applications for most of the examples, to illustrate language fundamentals.

Summary

  • C# was initially created specifically for use with the .NET platform.

  • C# is used with the .NET Framework, which allows you access to a number of libraries that are specifically intended for use with Windows.

  • The Common Language Runtime (CLR) is the component of the .NET Framework that allows you to compile and execute applications written in either C# or Visual Basic .NET.

  • C# is designed to be simple, type-safe, object-oriented, and high-performance.

  • C# applications consist of human-readable source code, written in a text editor. The source code is compiled into Microsoft Intermediate Language (MSIL) which, at runtime, is compiled into machine code.

  • A namespace is a way of grouping the names that you assign to elements in your application so that they don't conflict with other names, either yours or those assigned by Microsoft or other developers.

  • Classes are the core building blocks of C# and object-oriented programming because they allow you to create new types that model types in the "problem domain"-that is, that model things in the area you are concerned with.

  • A method is a named block of code that performs an action and that may return a value.

  • A comment is a note for the programmer and does not affect the running of the application.

  • A string is a set of text characters enclosed in quotes.

  • You can use C# to develop console applications, Windows applications, web applications, and web services.

This chapter wasn't that long and yet you've come a very long way. You got a crash-course introduction to the C# language, and you saw a little of what went into creating it and what goes on underneath. Most important, though, you wrote, compiled, and ran a real working application. You can already call yourself a C# programmer. Granted, creating an application with Notepad and the command-line compiler is a bit painful, and there's no reason why you should be fumbling around with a unicycle when you've got a fully loaded Ferrari just waiting for you to slip behind the wheel. So, we're going to take just a quick break in the next chapter to show you around the Visual Studio IDE, and then we'll come right back to the fundamentals of the language.

Test Your Knowledge: Quiz

Question 1-1. What is the CLR?

Question 1-2. What is the .NET Framework?

Question 1-3. What does it mean to say that C# is a "safe" language?

Question 1-4. What is a keyword?

Question 1-5. What does the compiler do?

Question 1-6. What is MSIL?

Question 1-7. What is the JIT?

Question 1-8. What is a namespace?

Question 1-9. What is a string?

Question 1-10. What are the four types of applications you can build in Visual Studio 2008?

Test Your Knowledge: Exercise

Exercise 1-1. Write an application that emits the words "What a great book!" to the console window.

Hint: open Visual Studio, create a console application, and, if you get stuck, consider copying or modifying the code shown in the chapter. Remember, these exercises are for your own edification, no one is grading them, and making mistakes is an opportunity to explore and learn more-this is true in just about everything except nuclear physics.

So, Don't Panic!