Buy this Book
Print Book $39.99 Read it Now!
Print Book £28.50
Add to UK Cart
Reprint Licensing

Learning C# 2005
Learning C# 2005, Second Edition Get Started with C# 2.0 and .NET Programming

By Jesse Liberty, Brian MacDonald
Price: $39.99 USD
£28.50 GBP

Cover | Table of Contents


Table of Contents

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.
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.
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.
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.
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.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
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.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
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.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
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.
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).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
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.
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.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
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.
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/
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
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.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
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 complier. 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.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
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.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
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.
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.
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.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
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.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
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.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
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?
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
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!
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Visual Studio 2005
In Chapter 1, you learned that you can create your C# applications using Notepad. In this chapter, you'll learn why you never will. Microsoft developed Visual Studio 2005 to facilitate the creation of Windows and web applications. You will find that this Integrated Development Environment (IDE) is a very powerful tool that will greatly simplify your work.
Visual Studio 2005 offers many advantages to the .NET developer, among them:
  • A modern interface, using a tabbed document metaphor for code and layout screens, and dockable toolbars and information windows.
  • Convenient access to multiple design and code windows (this will make more sense when you are creating web applications, as shown in Chapter 19).
  • WYSIWYG (What You See Is What You Get) visual design of Windows and Web Forms.
  • Code completion, which allows you to enter code with fewer errors and less typing.
  • IntelliSense, which displays tips for every method, providing the return type and the types of all the parameters.
  • Dynamic, context-sensitive help, which allows you to view topics and samples relevant to the code you are writing at the moment. You can also search the complete SDK library from within the IDE.
  • Immediate flagging of syntax errors, which allows you to fix problems as they are entered.
  • A Start Page, which provides easy access to new and existing projects.
  • The same code editor for all .NET languages, which shortens the learning curve. Each language can have specialized aspects, but all languages benefit from shared features, such as incremental search, code outlining, collapsing text, line numbering, and color-coded keywords.
  • An HTML editor, which provides both Design and HTML views that update each other in real time.
  • A Solution Explorer, which displays in outline form all the files comprising your solution.
  • An integrated debugger, which allows you to step through code, observe program runtime behavior, and set breakpoints, even across multiple languages and multiple processes.
  • Customization capability, which allows you to set user preferences for IDE appearance and behavior.
  • Integrated support for source control software.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Before You Read Further
This chapter has a lot of information in it, and you won't need all of it all at once. In fact, much of the information will not even apply to console applications, but will be valuable when you are ready to create Windows or web applications.
Many readers like to skim this chapter the first time through, and then come back for the details later. But it is your book, you paid for it (you did pay for it, didn't you?), and so you are free to read the entire chapter, take notes as you go, skip it entirely, or otherwise use it to your best advantage.
Whether or not you read this chapter, I do strongly recommend you spend time (lots and lots of time) exploring Visual Studio in detail. You will forever be surprised at how much is in there and how much you can set it up to behave as you want; it is your principal development tool. Ignoring Visual Studio would be like a race car driver never looking under the hood. In time, you not only want to know how to change the oil, but you also want to understand how the valves work and why the linkage sticks.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Start Page
The Start Page is the first thing you see when you open Visual Studio 2005 (unless you configure it otherwise). From here, you can create new projects or open a project you worked on in a previous session. You can also find out what is new in .NET, access .NET newsgroups and web sites, search for help online, download useful code, or adjust Visual Studio 2005 to your personal requirements. Figure 2-1 shows a typical Start Page.
The Start Page includes a list of recent projects (clicking on one will open it), along with the ability to open any project on your computer or to create a new one. The Getting Started box provides links to features and helpful sites, and the large box on the right contains useful articles from MSDN online.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Projects and Solutions
A C# program is built from source files, which are text files containing the code you write. Source code files are named with the .cs extension. The HelloWorld.cs file you created in Chapter 1 is an example.
A typical Visual Studio 2005 application can have a number of other files (such as assembly information files, references, icons, data connections, and more). Visual Studio 2005 organizes these files into a container called a project.
Figure 2-1: Visual Studio start page
Visual Studio 2005 provides two types of containers for your source code, folders, files, and related material: the project and the solution. A project is a set of files that work together to create an executable program (.exe) or a dynamic link library (.dll). Large, complex projects may contain multiple .dll files.
A solution is a set of related projects, although it may also have just one project. Each time you create a new project, Visual Studio 2005 either adds it to an existing solution or creates a new solution.
Solutions are defined within a file named for the solution, and have the extension .sln. The .sln file contains metadata, which is basically information about the data. The metadata describes the projects that compose the solution and information about building the solution.
Visual Studio 2005 also creates a file with the same base name as the .sln file, but with the filename extension .sou (such as mySolution.sln and mySolution.sou). The .sou file contains metadata used to customize the IDE.
There are a number of ways to open an existing solution. The simplest way is to select Open Project from the Start menu (which opens a project and its enclosing solution). Alternatively, you can open a solution in Visual Studio 2005 just by double-clicking the .sln file in Windows Explorer.
Typically, the build process results in the contents of a project being compiled into an executable (.exe) file or a dynamic link library (.dll) file. This book focuses on creating executable files.
The metadata describing the project is contained in a separate file named after the project with the extension .
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Inside the Integrated Development Environment
The Visual Studio 2005 Integrated Development Environment (IDE) is centered around an editor. An editor is much like a word processor, except that it produces simple text (that is, text with no formatting, such as bold and italics). All source code files are simple text files.
The Visual Studio 2005 IDE also provides support for building Graphical User Interfaces (GUIs ) , which are integral to Windows and web projects. The following pages introduce some of the key features of the IDE.
The IDE is a Multiple Document Interface (MDI ) application. There is a main window, and within the main window are a number of smaller windows. The central window is the text editing window. Figure 2-3 shows the basic layout.
Figure 2-3: The IDE
To the left of the editing window are a number of tabbed windows that contain tools used when creating Windows and web applications. To the right of the editing window are both stacked and tabbed windows. Shown on top is the Solution Explorer , which allows you to examine and manipulate the files in the solution. Below the Solution Explorer are two tabbed windows: Dynamic Help and Properties . The Properties window is used extensively when creating web and Windows desktop applications. Dynamic help will examine what you are doing and offer help on related topics.
At the bottom of the IDE are five tabbed windows: Error List , Task List , Output , Find Results , and Find Symbol Results .
All of these windows, plus the Toolbox, are resizable and dockable. They can be resized by placing the mouse cursor over the edge you want to move. The cursor will change to a double-arrow resizing cursor, at which point you can drag the window edge one way or the other.
Right-clicking on the title bar of a dockable window pops up a menu with five mutually exclusive check items:
Floating
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Building and Running
You can run your application at any time by selecting either Start or Start Without Debugging from the Debug menu , or you can accomplish the same results by pressing either F5 or Ctrl-F5, respectively. You can also start the program by clicking the Start icon (▸) on the Standard toolbar.
For console applications , the advantage of running the program with Ctrl-F5 is that Visual Studio 2005 will open your application in a console window, display its results, and then add a line to press a key when you are ready, as shown in Figure 2-5. This keeps the window open until you've seen the results and pressed a key, at which point the window will close.
The program can be built (that is, the .exe and .dll files can be generated) by selecting a command under the Build menu . You have the option of building the entire solution or only the currently selected project.
Figure 2-5: Running the application
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Menus and Toolbars
The menus provide access to many of the commands and capabilities of Visual Studio 2005. The more commonly used menu commands are duplicated with toolbar buttons for ease of use.
The menus and toolbars are context-sensitive (the available selection is dependent on what part of the IDE is currently selected, and what activities are expected or allowed). For example, if the current active window is a code-editing window for a console window, the top-level menu commands are: File , Edit , View, Refactor, Project, Build, Debug, Data, Tools, Test, Window, Community, and Help.
Many of the menu items have keyboard shortcuts, listed adjacent to the menu item itself. These are comprised of one or more keys (referred to as a chord), pressed simultaneously. Shortcut keys can be a huge productivity boost, because you can perform common tasks quickly, without removing your hands from the keyboard.
The following sections describe some of the more important menu items and their submenus, focusing on those aspects that are interesting and different from common Windows commands.
The File menu provides access to a number of file-, project-, and solution-related commands. Many of these commands are content-sensitive.
As in most Windows applications, the New menu item creates new items to be worked on by the application.
The Edit menu contains the text editing and searching commands that one would expect, but also includes commands useful in editing code. The most useful are discussed next.

Section 2.6.2.1: Cycle Clipboard Ring

The Clipboard Ring is like copy-and-paste on steroids. You can copy a number of different selections to the Windows clipboard, using the Edit → Cut (Ctrl-X) or Edit → Copy (Ctrl-C) commands. Then use Ctrl-Shift-V to cycle through all the selections, allowing you to paste the correct one when it comes around.
Visual Studio Hot Keys can be changed systematically or individually; the ones referred to here and throughout this book are the "standard keys" used when programming in C#. Your mileage may vary.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Summary
  • Visual Studio 2005 is a powerful tool with many features, to make writing programs easier.
  • The Start Page provides an overview of your programming environment, and a list of recent projects.
  • A solution is a set of related projects, and a project is a set of related code files and associated resources such as images, and so on.
  • Visual Studio 2005 has a number of templates that allow you to create particular types of projects, such as windows or web applications.
  • Among other things, Visual Studio 2005 provides "what you see is what you get" (WSYWYG) support for building, testing, and debugging graphical user interfaces (GUI).
  • Every window in Visual Studio 2005 can be resized and moved.
  • To run your application, select Start or Start Without Debugging, or press F5 or Ctrl-F5.
  • The Clipboard Ring can hold a number of different selections that you can cycle through.
  • The Find and Replace feature lets you locate text strings in the current file or other files, using normal text or regular expressions.
  • Bookmarks enable you to mark spots in your code so you can easily find them later.
  • IntelliSense saves you keystrokes and can help you discover methods and required arguments by (for example) listing possible completions to what you're typing.
  • The Properties window displays properties for the currently selected item.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Quiz
Question 2–1.
What is the difference between a project and a solution?
Question 2–2.
How do you move windows in the IDE?
Question 2–3.
What does the pushpin do on a window?
Question 2–4.
What is the difference between pressing F5 and Ctrl-F5 from within Visual Studio 2005?
Question 2–5.
What is the Clipboard Ring?
Question 2–6.
How do you retrieve items from the clipboard ring?
Question 2–7.
What is "Find Symbol" for?
Question 2–8.
What are bookmarks?
Question 2–9.
What is IntelliSense?
Question 2–10.
What is a code snippet?
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Exercise
Exercise 2-1.
Insert a bookmark before the Console.Writeline( ) statement in Hello World. Navigate away from it and then use the bookmarks menu item to return to it.
Exercise 2-2.
Undock the Solution Explorer window from the right side of the IDE and move it to the left. Leave it there if you like, or move it back.
Exercise 2-3.
Insert a code snippet for a for loop from the Edit → Intellisense menu into your Hello World program. (It won't do anything for now; you'll learn about for loops in Chapter 4.)
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: C# Language Fundamentals
Chapter 1 demonstrates a very simple C# program that prints the text string "Hello world!" to the console screen and provides a line-by-line analysis of that program. However, even that very simple program was complex enough that some of the details had to be skipped over. In this chapter, I'll begin an in-depth exploration of the syntax and structure of the C# language. The syntax of a language is the order of the keywords, where you put semicolons and so forth. The semantics is what you are expressing in the code, and how your code fits together. Syntax is trivial and unimportant, but because compilers are absolute sticklers for correct syntax, novice programmers spend a lot of attention to syntax until they are comfortable. Fortunately, Visual Studio 2005 makes managing syntax much easier so that you can focus on semantics, which is far more important.
In this chapter, I'll introduce statements and expressions, the building blocks of any program. You'll learn about variables and constants, which let you store values for use in your program. I'll begin an explanation of types and we'll take a look at strings, which you saw briefly in the Hello World program.
In C#, a complete program instruction is called a statement and each statement ends with a semicolon (;) . Programs consist of sequences of statements such as:
    int myVariable;                   // a statement
    myVariable = 23;                  // another statement
    int anotherVariable = myVariable; // yet another statement
The compiler starts at the beginning of a source code file and reads down, executing statement after statement in the order encountered. This would be entirely straightforward, and terribly limiting, were it not for branching . Branching allows you to change the order in which statements are evaluated. See Chapter 5 for more information about branching.
C# is a strongly typed language. That means that every object you create or use in a C# program must have a specific type (e.g., you must declare the object to be an integer or a string or a Dog or a Button). Essentially, the type indicates how big the object is (in memory) and what it can do.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Statements
In C#, a complete program instruction is called a statement and each statement ends with a semicolon (;) . Programs consist of sequences of statements such as:
    int myVariable;                   // a statement
    myVariable = 23;                  // another statement
    int anotherVariable = myVariable; // yet another statement
The compiler starts at the beginning of a source code file and reads down, executing statement after statement in the order encountered. This would be entirely straightforward, and terribly limiting, were it not for branching . Branching allows you to change the order in which statements are evaluated. See Chapter 5 for more information about branching.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Types
C# is a strongly typed language. That means that every object you create or use in a C# program must have a specific type (e.g., you must declare the object to be an integer or a string or a Dog or a Button). Essentially, the type indicates how big the object is (in memory) and what it can do.
Types come in two flavors: those that are built into the language (intrinsic types ) and those you create (classes and interfaces, discussed in Chapters 7 and 13). C# offers a number of intrinsic types, shown in Table 3-1.
Table 3-1: The intrinsic types
C# type
Size (in bytes)
.NET type
Description
byte
1
Byte
Unsigned (values 0-255).
char
2
Char
Unicode characters.
bool
1
Boolean
True or false.
sbyte
1
SByte
Signed (values -128 to 127).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Variables
A variable is an instance of an intrinsic type (such as int) that can hold a value:
    int myVariable = 15;
You initialize a variable by writing its type, its identifier, and then assigning a value to that variable.
An identifier is just an arbitrary name you assign to a variable, method, class, or other element. In this case, the variable's identifier is myVariable.
You can define variables without initializing them:
    int myVariable;
You can then assign a value to myVariable later in your program:
    int myVariable;
    // some other code here
    myVariable = 15; // assign 15 to myVariable
You can also change the value of a variable later in the program. That is why they're called variables; their values can vary.
    int myVariable;
    // some other code here
    myVariable = 15; // assign 15 to myVariable
    // some other code here
    myVariable = 12; // now it is 12
Technically, a variable is a named storage location (that is, stored in memory) with a type. After the final line of code in the previous example, the value 12 is stored in the named location myVariable.
Example 3-1 illustrates the use of variables. To test this program, open Visual Studio .NET and create a console application. Type in the code as shown.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Definite Assignment
Content preview·Buy PDF of this chapter|