Wiley | 978-0-470-19135-4 | Datasheet | Wiley Beginning Microsoft Visual C# 2008

Part I
AL
The C# Language
Chapter 1: Introducing C#
D
Chapter 5: More About Variables
TE
Chapter 4: Flow Control
MA
Chapter 3: Variables and Expressions
RI
Chapter 2: Writing a C# Program
TE
Chapter 6: Functions
GH
Chapter 7: Debugging and Error Handling
Chapter 8: Introduction to Object-Oriented Programming
RI
Chapter 9: Defining Classes
PY
Chapter 10: Defining Class Members
CO
Chapter 11: Collections, Comparisons, and Conversions
Chapter 12: Generics
Chapter 13: Additional OOP Techniques
Chapter 14: C# 3.0 Language Enhancements
1
Introducing C#
Welcome to the first chapter of the first section of this book. This section will provide you with the
basic knowledge you need to get up and running with C#. This chapter provides an overview of
C# and the .NET Framework, including what these technologies are, the motivation for using
them, and how they relate to each other.
First is a general discussion of the .NET Framework. This technology contains many concepts that
are tricky to come to grips with initially. This means that the discussion, by necessity, covers many
new concepts in a short amount of space. However, a quick look at the basics is essential to
understanding how to program in C#. Later in the book you will revisit many of the topics covered
here, exploring them in more detail.
After that general introduction, the chapter provides a basic description of C# itself, including its
origins and similarities to C++. Finally, you look at the primary tools used throughout this book:
Visual Studio 2008 (VS) and Visual C# 2008 Express Edition (VCE).
What Is the .NET Framework?
The .NET Framework is a new and revolutionary platform created by Microsoft for developing
applications. The most interesting thing about this statement is how vague it is — but there are
good reasons for this. For a start, note that it doesn’t “develop applications on the Windows
operating system.” Although the Microsoft release of the .NET Framework runs on the Windows
operating system, it is fast becoming possible to find alternative versions that will work on other
systems. One example of this is Mono, an open-source version of the .NET Framework (including
a C# compiler) that runs on several operating systems, including various flavors of Linux and Mac
OS. More such projects are in the pipeline and may be available by the time you read this. In
addition, you can use the Microsoft .NET Compact Framework (essentially a subset of the full
.NET Framework) on personal digital assistant (PDA) class devices and even some smartphones.
One of the key motivations behind the .NET Framework is its intended use as a means of
integrating disparate operating systems.
Part I: The C# Language
In addition, the preceding definition of the .NET Framework includes no restriction on the type of
applications that are possible. That’s because there is no restriction — the .NET Framework allows the
creation of Windows applications, Web applications, Web services, and pretty much anything else you
can think of.
The .NET Framework has been designed so that it can be used from any language, including C# (the
subject of this book) as well as C++, Visual Basic, JScript, and even older languages such as COBOL. For
this to work, .NET-specific versions of these languages have also appeared, and more are being released
all the time. Not only do all of these have access to the .NET Framework, but they can also communicate
with each other. It is perfectly possible for C# developers to make use of code written by Visual Basic
programmers, and vice versa.
All of this provides a hitherto unthinkable level of versatility and is part of what makes using the .NET
Framework such an attractive prospect.
What’s in the .NET Framework?
The .NET Framework consists primarily of a gigantic library of code that you use from your client
languages (such as C#) using object-oriented programming (OOP) techniques. This library is categorized
into different modules — you use portions of it depending on the results you want to achieve. For
example, one module contains the building blocks for Windows applications, another for network
programming, and another for Web development. Some modules are divided into more specific
submodules, such as a module for building Web services within the module for Web development.
The intention is for different operating systems to support some or all of these modules, depending on
their characteristics. A PDA, for example, would include support for all the core .NET functionality, but
is unlikely to require some of the more esoteric modules.
Part of the .NET Framework library defines some basic types. A type is a representation of data, and
specifying some of the most fundamental of these (such as “a 32-bit signed integer”) facilitates
interoperability between languages using the .NET Framework. This is called the Common Type
System (CTS).
As well as supplying this library, the .NET Framework also includes the .NET Common Language Runtime
(CLR), which is responsible for maintaining the execution of all applications developed using the .NET
library.
Writing Applications Using the .NET Framework
Writing an application using the .NET Framework means writing code (using any of the languages that
support the Framework) using the .NET code library. In this book you use VS and VCE for your
development — VS is a powerful, integrated development environment that supports C# (as well as
managed and unmanaged C++, Visual Basic, and some others). VCE is a slimmed down (and free)
version of VS that supports C# only. The advantage of these environments is the ease with which .NET
features can be integrated into your code. The code that you create will be entirely C# but will use the
.NET Framework throughout, and you’ll make use of the additional tools in VS and VCE where
necessary.
4
Chapter 1: Introducing C#
For C# code to execute, it must be converted into a language that the target operating system
understands, known as native code. This conversion is called compiling code, an act that is performed by a
compiler. Under the .NET Framework, however, this is a two-stage process.
MSIL and JIT
When you compile code that uses the .NET Framework library, you don’t immediately create operating
system–specific native code. Instead, you compile your code into Microsoft Intermediate Language (MSIL)
code. This code isn’t specific to any operating system and isn’t specific to C#. Other .NET languages —
Visual Basic .NET, for example — also compile to this language as a first stage. This compilation step is
carried out by VS or VCE when you develop C# applications.
Obviously, more work is necessary to execute an application. That is the job of a Just-in-Time (JIT)
compiler, which compiles MSIL into native code that is specific to the OS and machine architecture being
targeted. Only at this point can the OS execute the application. The just-in-time part of the name reflects
the fact that MSIL code is only compiled as, and when, it is needed.
In the past, it was often necessary to compile your code into several applications, each of which targeted
a specific operating system and CPU architecture. Often, this was a form of optimization (to get code to
run faster on an AMD chipset, for example), but at times it was critical (for applications to work in both
Win9x and WinNT/2000 environments, for example). This is now unnecessary, because JIT compilers (as
their name suggests) use MSIL code, which is independent of the machine, operating system, and CPU.
Several JIT compilers exist, each targeting a different architecture, and the appropriate one will be used
to create the native code required.
The beauty of all this is that it requires a lot less work on your part — in fact, you can forget about
system-dependent details and concentrate on the more interesting functionality of your code.
Assemblies
When you compile an application, the MSIL code created is stored in an assembly. Assemblies include
both executable application files that you can run directly from Windows without the need for any other
programs (these have a .exe file extension), and libraries (which have a .dll extension) for use by other
applications.
In addition to containing MSIL, assemblies also include meta information (that is, information about the
information contained in the assembly, also known as metadata) and optional resources (additional data
used by the MSIL, such as sound files and pictures). The meta information enables assemblies to be fully
self-descriptive. You need no other information to use an assembly, meaning you avoid situations such
as failing to add required data to the system registry and so on, which was often a problem when
developing with other platforms.
This means that deploying applications is often as simple as copying the files into a directory on a
remote computer. Because no additional information is required on the target systems, you can just run
an executable file from this directory and (assuming the .NET CLR is installed) you’re good to go.
Of course, you won’t necessarily want to include everything required to run an application in one place.
You might write some code that performs tasks required by multiple applications. In situations like that,
it is often useful to place the reusable code in a place accessible to all applications. In the .NET
Framework, this is the Global Assembly Cache (GAC). Placing code in the GAC is simple — you just place
the assembly containing the code in the directory containing this cache.
5
Part I: The C# Language
Managed Code
The role of the CLR doesn’t end once you have compiled your code to MSIL, and a JIT compiler has
compiled that to native code. Code written using the .NET Framework is managed when it is executed
(a stage usually referred to as runtime). This means that the CLR looks after your applications by
managing memory, handling security, allowing cross-language debugging, and so on. By contrast,
applications that do not run under the control of the CLR are said to be unmanaged, and certain languages
such as C++ can be used to write such applications, which, for example, access low-level functions of the
operating system. However, in C# you can write only code that runs in a managed environment. You will
make use of the managed features of the CLR and allow .NET itself to handle any interaction with the
operating system.
Garbage Collection
One of the most important features of managed code is the concept of garbage collection. This is the .NET
method of making sure that the memory used by an application is freed up completely when the
application is no longer in use. Prior to .NET this was mostly the responsibility of programmers, and a
few simple errors in code could result in large blocks of memory mysteriously disappearing as a result of
being allocated to the wrong place in memory. That usually meant a progressive slowdown of your
computer followed by a system crash.
.NET garbage collection works by inspecting the memory of your computer ever so often and
removing anything from it that is no longer needed. There is no set time frame for this; it might happen
thousands of times a second, once every few seconds, or whenever, but you can rest assured that it
will happen.
There are some implications for programmers here. Because this work is done for you at an
unpredictable time, applications have to be designed with this in mind. Code that requires a lot of
memory to run should tidy itself up, rather than wait for garbage collection to happen, but that isn’t as
tricky as it sounds.
Fitting It Together
Before moving on, let’s summarize the steps required to create a .NET application as discussed
previously:
1.
Application code is written using a .NET-compatible language such as C# (see Figure 1-1).
C#code
Figure 1-1
6
Chapter 1: Introducing C#
2.
That code is compiled into MSIL, which is stored in an assembly (see Figure 1-2).
C#application
code
Compilation
Assembly
Figure 1-2
3.
When this code is executed (either in its own right if it is an executable or when it is used from
other code), it must first be compiled into native code using a JIT compiler (see Figure 1-3).
Assembly
JIT Compilation
Native Code
Figure 1-3
4.
The native code is executed in the context of the managed CLR, along with any other running
applications or processes, as shown in Figure 1-4.
System Runtime
.NET CLR
Native Code
Native Code
Native Code
Figure 1-4
Linking
Note one additional point concerning this process. The C# code that compiles into MSIL in step 2 needn’t
be contained in a single file. It’s possible to split application code across multiple source code files, which
are then compiled together into a single assembly. This extremely useful process is known as linking. This
is because it is far easier to work with several smaller files than one enormous one. You can separate out
logically related code into an individual file so that it can be worked on independently and then
7
Part I: The C# Language
practically forgotten about when completed. This also makes it easy to locate specific pieces of code
when you need them and enables teams of developers to divide up the programming burden into
manageable chunks, whereby individuals can “check out” pieces of code to work on without risking
damage to otherwise satisfactory sections or sections other people are working on.
What Is C#?
C#, as mentioned earlier, is one of the languages you can use to create applications that will run in the
.NET CLR. It is an evolution of the C and C++ languages and has been created by Microsoft specifically
to work with the .NET platform. Because it is a recent development, the C# language has been designed
with hindsight, taking into account many of the best features from other languages, while clearing up
their problems.
Developing applications using C# is simpler than using C++, because the language syntax is simpler.
Still, C# is a powerful language, and there is little you might want to do in C++ that you can’t do in C#.
Having said that, those features of C# that parallel the more advanced features of C++, such as directly
accessing and manipulating system memory, can only be carried out using code marked as unsafe. This
advanced programmatic technique is potentially dangerous (hence its name), because it is possible to
overwrite system-critical blocks of memory with potentially catastrophic results. For this reason, and
others, this book does not cover that topic.
At times, C# code is slightly more verbose than C++. This is a consequence of C# being a type-safe
language (unlike C++). In layperson’s terms, this means that once some data has been assigned to a type,
it cannot subsequently transform itself into another unrelated type. Consequently, strict rules must be
adhered to when converting between types, which means you will often need to write more code to
carry out the same task in C# than you might write in C++, but you get two benefits: the code is more
robust and debugging is simpler, and .NET can always track the type of a piece of data at any time.
In C#, you therefore may not be able to do things such as “take the region of memory 4 bytes into this
data and 10 bytes long and interpret it as X,” but that’s not necessarily a bad thing.
C# is just one of the languages available for .NET development, but it is certainly the best. It has the
advantage of being the only language designed from the ground up for the .NET Framework and may
be the principal language used in versions of .NET that are ported to other operating systems. To keep
languages such as the .NET version of Visual Basic as similar as possible to their predecessors yet
compliant with the CLR, certain features of the .NET code library are not fully supported. By contrast,
C# can make use of every feature that the .NET Framework code library has to offer. The latest version of
.NET includes several improvements to the C# language, partly in response to requests from developers,
making it even more powerful.
Applications You Can Write with C#
The .NET Framework has no restrictions on the types of applications that are possible, as discussed
earlier. C# uses the framework and therefore has no restrictions on possible applications. However, here
are a few of the more common application types:
❑
8
Windows applications: These are applications, such as Microsoft Office, that have a familiar
Windows look and feel about them. This is made simple by using the Windows Forms module
of the .NET Framework, which is a library of controls (such as buttons, toolbars, menus, and so
on) that you can use to build a Windows user interface (UI).
Chapter 1: Introducing C#
❑
Web applications: These are Web pages such as might be viewed through any Web browser. The
.NET Framework includes a powerful system for generating Web content dynamically, allowing
personalization, security, and much more. This system is called ASP.NET (Active Server Pages
.NET), and you can use C# to create ASP.NET applications using Web Forms.
❑
Web services: These are a new and exciting way to create versatile distributed applications.
Using Web services you can exchange virtually any data over the Internet, using the same
simple syntax regardless of the language used to create a Web service or the system that it
resides on.
Any of these types may also require some form of database access, which can be achieved using the
ADO.NET (Active Data Objects .NET) section of the .NET Framework or through the new LINQ
(Language Integrated Query) capabilities of C#. Many other resources can be drawn on, such as tools for
creating networking components, outputting graphics, performing complex mathematical tasks, and so on.
C# in This Book
The first part of this book deals with the syntax and usage of the C# language without too much
emphasis on the .NET Framework. This is necessary because you won’t be able to use the .NET
Framework at all without a firm grounding in C# programming. We’ll start off even simpler, in fact, and
leave the more involved topic of object-oriented programming (OOP) until you’ve covered the basics.
These are taught from first principles, assuming no programming knowledge at all.
Once you have done that, you’ll be ready to move on to developing the types of applications listed in the
last part. Part 2 of this book looks at Windows Forms programming, Part 3 tackles Web application and
Web service programming, Part 4 examines data access (for database, file system, and XML data), and
Part 5 covers some other .NET topics of interest, such as more about assemblies and graphics
programming.
Visual Studio 2008
In this book, you use the Visual Studio 2008 (VS) or Visual C# 2008 Express Edition (VCE) development
tools for all of your C# programming, from simple command-line applications to more complex project
types. A development tool, or Integrated Development Environment (IDE), such as VS isn’t essential for
developing C# applications, but it makes things much easier. You can (if you want to) manipulate C#
source code files in a basic text editor, such as the ubiquitous Notepad application, and compile code
into assemblies using the command-line compiler that is part of the .NET Framework. However, why do
this when you have the power of an IDE to help you?
The following is a short list of some Visual Studio features that make it an appealing choice for .NET
development:
❑
VS automates the steps required to compile source code but at the same time gives you complete
control over any options used should you wish to override them.
❑
The VS text editor is tailored to the languages VS supports (including C#) so that it can
intelligently detect errors and suggest code where appropriate as you are typing. This feature is
called IntelliSense.
9
Part I: The C# Language
❑
VS includes designers for Windows Forms and Web Forms applications, enabling simple
drag-and-drop design of UI elements.
❑
Many types of C# projects may be created with “boilerplate” code already in place. Instead of
starting from scratch, you will often find that various code files are started for you, reducing the
amount of time spent getting started on a project. This is especially true of the new “Starter Kit”
project type, which enables you to develop from a fully functional application base. Some starter
kits are included with the VS installation, and you can find plenty more online to play with.
❑
VS includes several wizards that automate common tasks, many of which can add appropriate
code to existing files without you having to worry about (or even, in some cases, remember) the
correct syntax.
❑
VS contains many powerful tools for visualizing and navigating through elements of your
projects, whether they are C# source code files or other resources such as bitmap images or
sound files.
❑
As well as simply writing applications in VS, you can create deployment projects, making it easy
to supply code to clients and for them to install it without much trouble.
❑
VS enables you to use advanced debugging techniques when developing projects, such as the
capability to step through code one instruction at a time while keeping an eye on the state of
your application.
There is much more than this, but you get the idea!
Visual Studio 2008 Express Products
In addition to Visual Studio 2008, Microsoft also supplies several simpler development tools known as
Visual Studio 2008 Express Products. These are freely available at http://lab.msdn.microsoft
.com/express.
Two of these products, Visual C# 2008 Express Edition and Visual Web Developer 2008 Express Edition,
together enable you to create almost any C# application you might need. They both function as
slimmed-down versions of VS and retain the same look and feel. While they offer many of the same
features as VS, some notable feature are absent, although not so many that they would prevent you from
using these tools to work through this book.
In this book you’ll use VCE to develop C# applications wherever possible, and only use VS where it is
necessary for certain functionality.
Solutions
When you use VS or VCE to develop applications, you do so by creating solutions. A solution, in VS and
VCE terms, is more than just an application. Solutions contain projects, which might be Windows Forms
projects, Web Form projects, and so on. Because solutions can contain multiple projects, you can group
together related code in one place, even if it will eventually compile to multiple assemblies in various
places on your hard disk.
10
Chapter 1: Introducing C#
This is very useful because it enables you to work on shared code (which might be placed in the GAC) at
the same time as applications that use this code. Debugging code is a lot easier when only one
development environment is used, because you can step through instructions in multiple code modules.
Summar y
In this chapter, you looked at the .NET Framework in general terms and discovered how it makes it easy
for you to create powerful and versatile applications. You saw what is necessary to turn code in
languages such as C# into working applications and what benefits you gain from using managed code
running in the .NET Common Language Runtime.
You also learned what C# actually is and how it relates to the .NET Framework, and you were
introduced to the tools that you’ll use for C# development — Visual Studio 2008 and Visual C# 2008
Express Edition.
In this chapter, you learned the following:
❑
What the .NET Framework is, why it was created, and what makes it such an attractive
environment to program in
❑
What C# is and what makes it an ideal tool to program in the .NET Framework
❑
What you need to develop .NET applications effectively — namely, a development environment
such as VS or VCE
In the next chapter, you get some C# code running, which will give you enough knowledge to sit back
and concentrate on the C# language itself, rather than worry too much about how the IDE works.
11
Download PDF

advertising