Chapter 1. C# and .NET Programming

Learning C# 2005 introduces C# 2005 and the .NET 2.0 development platform. This book is targeted at new programmers and those migrating from VB6 or from non-object-oriented languages. Along the way, you will learn a great deal about writing high-quality, industrial-strength programs for .NET.

Tip

Programmers migrating from Java or C++ may find the material in Programming C# by Jesse Liberty (O’Reilly, 2005) a more appropriate fit for their skills.

This brief introduction will show you how C# fits into the .NET picture, what you can do with the language, and what benefits this language has over its predecessors.

Tip

Unless otherwise specified, when we refer to C#, we mean C# 2005; when we refer to .NET, we mean the .NET 2005 (.NET 2.0) Framework; and when we refer to Visual Studio, we mean Visual Studio 2005.

Finally, when we refer to using Visual Studio 2005, you may well be using Visual C# 2005 Express instead.

In the following pages, you will also learn some of the concepts integral to object-oriented programming, which has revolutionized how web and Windows applications are developed. Object-oriented programming is closely tied to the semantics of the C# language; that is, the meaning behind the code you write. Obviously, you need to have a basic understanding of the syntax of the C# language, but you also need to understand what you are actually trying to accomplish. This book will explain it all, in the context of creating applications to run either on the Web or on a Windows desktop.

C# 2005 and .NET 2.0

In the past, you might have learned a language like C or Java without much concern about the platform on which you would be programming. These cross-platform languages were as comfortable on a Unix box as they were on a PC running Windows.

C#, however, was created specifically for .NET. Although .NET may become cross-platform some day soon—there already exists a working open-source Unix version—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. Their 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 in 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 controls that you can drag onto your form, and they will do all the heavy lifting for you.

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

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

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

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

The .NET 2.0 Framework

Central to the .NET platform is a development environment known as the .NET Framework . The Framework specifies how .NET programming constructs such as intrinsic types, classes, and interfaces are implemented. You will learn about these constructs 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 Common Language Runtime (CLR), described in the preceding section, 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.

Tip

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

The C# Language

The C# language is disarmingly simple, but C# is highly expressive when it comes to implementing modern programming concepts. C# includes all the support for structured, component-based, object-oriented programming that one expects of a modern language built on the shoulders of C++ and Java.

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 for client/server programming.

The goal of C# is to provide a simple, safe, object-oriented, Internet-centric, high-performance language for .NET development. C# is simple because there are relatively few keywords. This makes it easy to learn and easy to adapt to your specific needs.

Tip

Keywords are special words reserved by the language that have a specific meaning within all C# programs. Keywords include if, while, and for. You’ll learn about these keywords in the coming chapters.

C# is considered safe because the language is type-safe, an important mechanism to help you find bugs early in the development process. This makes for code that is easier to maintain and programs that are more reliable. C# 2005 was enhanced in many ways, one of which was to add support for generics (see Chapter 14), which makes collections type-safe as well, thus greatly improving the reliability of advanced applications.

C# was designed, from the very start, to support object-oriented programming. This book will 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 for developing web and web-aware programs. The Internet is a primary resource in most .NET applications.

The Structure of C# Applications

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. A classic text editor is Notepad.

Example 1-1 shows an example of a very simple source code file.

Example 1-1. A source code file
namespace NotePad
{
  class HelloWorld
  {
    // every console app starts with Main
    static void Main(  )
    {
      System.Console.WriteLine("Hello world!");
    }
  }
}

This program is explained in detail below. For now, observe that 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.

Once you write your program in an editor, you must compile it. For that, you need a compiler (explained shortly). Once compiled, your program must be run and tested.

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

Tip

The overwhelming majority of C# programmers will be building Windows and web applications for the .NET platform using the Visual Studio 2005, and all the examples for this book have been tested in that environment.

A free version of this popular product, called Visual C# 2005 Express Edition, is available for download at http://msdn.microsoft.com/vstudio/express/visualcsharp/.

There are excellent open source C# compilers available, such as those from the Mono project (http://www.mono-project.com) and SharpDevelop (http://www.icsharpcode.net/OpenSource/SD/). Everything in this book should work with those compilers, but we have not tested with them and can not guarantee 100% compatibility.

The Development Environment

The Visual Studio 2005 Integrated Development Environment (IDE) provides enormous advantages to the C# programmer. This book tacitly assumes that you’ll use Visual Studio 2005 for your work. However, the discussion focuses more on the language and the platform than on the tools.

Nonetheless, Chapter 2 provides an introduction to the IDE in some detail. Chapter 9 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, which display no graphics

  • Windows applications, which use the standard Windows interface

  • Web applications, which can be accessed with a browser

  • Web services, which can be accessed using standard Internet protocols and which provide services such as current stock quotes, ISBN to title conversions, etc., that can be used by other applications

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. The last two chapters will show you how to use C# within the context of building Windows and web applications, respectively.

The .NET platform is web-centric. The C# language was developed to allow .NET programmers to create very large, powerful, high-quality web applications quickly and easily. The .NET technology for creating web applications and web services is called ASP.NET.

Typically, you’ll create an ASP.NET application when you want your program to be available to end users on any platform (e.g., Windows , Mac, Unix). By serving your application over the Web, end users can access your program with any browser.

When you want the richness and power of a native application running directly on the Windows platform, you will create a desktop Windows application. The .NET tools for building Windows applications are called Windows Forms.

However, if you don’t need a Graphical User Interface (GUI) and just want to write a simple application that writes to a console window (i.e., what we used to call a DOS box), you might consider creating a console application. This book makes extensive use of console applications to illustrate the basics of the C# language.

Console applications

A console application runs in a console window, as shown in Figure 1-1. A console window (or DOS box) provides simple text-based output. Console applications are very helpful when learning a language because they strip away the distraction of the Graphical User Interface. 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. All these topics will be covered in detail in later chapters.

A console application
Figure 1-1. A console application
Windows applications

A Windows application runs on a PC’s desktop. You are already familiar with Windows applications such as Microsoft Word or 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. Figure 1-2 shows the output of a simple Windows application.

ASP.NET applications

An ASP.NET application runs on a web server and delivers its functionality through a browser, typically over the Web. ASP.NET technology facilitates developing web applications quickly and easily. Figure 1-3 shows a message from a simple ASP.NET application.

A Windows application
Figure 1-2. A Windows application
An ASP.NET application
Figure 1-3. An ASP.NET application

Although most commercial applications will be either Windows or ASP.NET programs, console applications have a tremendous advantage in a C# primer. Windows and ASP.NET applications bring a lot more overhead; there is great complexity in managing the window and all the events associated with the window. (Events are covered in Chapter 17.) Console applications keep things simple—allowing you to focus on the features of the language.

Tip

This book does not go into all the myriad details of building robust Windows and ASP.NET applications. For complete coverage of these topics, please see Programming ASP.NET and Programming .NET Windows Applications, both by Jesse Liberty and Dan Hurwitz (O’Reilly).

What’s in a Program?

A program consists of English-language instructions called source code . 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.

Your First Program: Hello World

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; it demonstrates some of the basic elements of a C# program.

Once you write your “Hello World” program and compile it, this chapter will provide a line-by-line analysis of the source code. This analysis gives something of a preview of the language; Chapter 3 describes the fundamentals much more fully.

As explained earlier, you can create C# programs with any text editor. You can, for example, create each of the three programs shown previously (in Figures 1-1, 1-2, and 1-3) with Notepad. To demonstrate that this is possible, you’ll write your very first C# program using Notepad.

Begin by opening Notepad and typing in the program exactly as shown in Example 1-2.

Example 1-2. Hello World in Notepad
namespace NotePad
{
   class HelloWorld
   {
      // every console app starts with Main
      static void Main(  )
      {
         System.Console.WriteLine("Hello world!");
      }
   }
}

That is the entire program. Save it to your disk as a file called helloworld.cs.

We’ll examine this program in some detail in just a moment. First, however, it must be compiled.

The Compiler

Once you save your program to disk, you must compile the code to create your application. Compiling your source code means running a compiler and identifying the source code file. You run the compiler by opening a command prompt (DOS box) and entering the program name csc. Then you “pass in” your source code file by entering the filename on the command line, as in the following:

    csc HelloWorld.cs

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 IL. When you run the program, the .NET Just In Time (JIT) compiler reads your IL code and produces an executable application in memory.

Tip

The IL code is actually stored in a .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.

Microsoft provides a command window with the correct environment variables set. Open the command window by selecting the following menu items in this order (your installation may vary slightly): Start → Programs → Microsoft Visual Studio 2005 → Visual Studio Tools → Visual Studio 2005 Command Prompt.

Navigate to the directory in which you created your code file and enter the following command:

    csc helloworld.cs

The Microsoft C# compiler compiles your code; when you display the directory, you’ll find the compiler has produced an executable file called helloworld.exe. Type helloworld at the command prompt, and your program executes, as shown in Figure 1-4.

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

Compiling and running Hello World
Figure 1-4. Compiling and running Hello World

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.

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).

Summary

  • C# was initially created specifically for use with the .NET platform but has been submitted to and been accepted by ECMA as a standardized programming language.

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

  • 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 run time, is compiled into machine code.

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

  • 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.

Quiz

Question 1–1.

What is the CLR?

Question 1–2.

What are the four types of applications you can build in .NET?

Question 1–3.

What is the .NET Framework?

Question 1–4.

What is the FCL?

Question 1–5.

What does it mean to say that C# is a “safe” language?

Question 1–6.

What is a keyword?

Question 1–7.

What is a namespace?

Question 1–8.

What does the compiler do?

Question 1–9.

What is MSIL?

Question 1–10.

What is the JIT?

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 (Written on the back of a tee shirt: “I am a nuclear technician. If I am running, try to keep up”).

So, Don’t Panic!

Get Learning C# 2005, 2nd Edition 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.