TM
C#
Your visual blueprint for
building .NET applications
by Eric Butow and Tommy Ryan
Published by
Hungry Minds, Inc.
909 Third Avenue
New York, NY 10022
Copyright © 2002 Hungry Minds, Inc.
Certain designs, text, and illustrations Copyright © 1992-2002 maranGraphics,
Inc., used with maranGraphics’ permission. All rights reserved. No part of this
book, including interior design, cover design, and icons, may be reproduced or
transmitted in any form, by any means (electronic, photocopying, recording, or
otherwise) without the prior written permission of the publisher.
maranGraphics, Inc.
5755 Coopers Avenue
Mississauga, Ontario, Canada
L4Z 1R9
Library of Congress Control Number: 2001089361
ISBN: 0-7645-3601-X
Printed in the United States of America
10 9 8 7 6 5 4 3 2 1
1V/QW/RR/QR/IN
Distributed in the United States by Hungry Minds, Inc.
Distributed by CDG Books Canada Inc. for Canada; by Transworld Publishers Limited
in the United Kingdom; by IDG Norge Books for Norway; by IDG Sweden Books for
Sweden; by IDG Books Australia Publishing Corporation Pty. Ltd. for Australia and
New Zealand; by TransQuest Publishers Pte Ltd. for Singapore, Malaysia, Thailand,
Indonesia, and Hong Kong; by Gotop Information Inc. for Taiwan; by ICG Muse, Inc.
for Japan; by Intersoft for South Africa; by Eyrolles for France; by International
REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS
OF THE CONTENTS OF THIS BOOK AND SPECIFICALLY DISCLAIM ANY IMPLIED WARRANTIES
OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. THERE ARE NO
WARRANTIES WHICH EXTEND BEYOND THE DESCRIPTIONS CONTAINED IN THIS
PARAGRAPH. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES REPRESENTATIVES
OR WRITTEN SALES MATERIALS. THE ACCURACY AND COMPLETENESS OF THE
INFORMATION PROVIDED HEREIN AND THE OPINIONS STATED HEREIN ARE NOT
GUARANTEED OR WARRANTED TO PRODUCE ANY PARTICULAR RESULTS, AND THE ADVICE
AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY INDIVIDUAL.
NEITHER THE PUBLISHER NOR AUTHOR SHALL BE LIABLE FOR ANY LOSS OF PROFIT OR ANY
OTHER COMMERCIAL DAMAGES, INCLUDING BUT NOT LIMITED TO SPECIAL, INCIDENTAL,
CONSEQUENTIAL, OR OTHER DAMAGES.
Trademark Acknowledgments
Permissions
Hungry Minds, the Hungry Minds logo, Visual, the Visual
logo, Read Less - Learn More and related trade dress are
registered trademarks or trademarks of Hungry Minds, Inc.,
in the United States and/or other countries and may not be
used without written permission. The maranGraphics logo
is a registered trademark or trademark of maranGraphics,
Inc. Visual Studio is a a registered trademark of Microsoft
Corporation. All other trademarks are the property of their
respective owners. Hungry Minds, Inc. and maranGraphics,
Inc. are not associated with any product or vendor
mentioned in this book.
FOR PURPOSES OF ILLUSTRATING THE CONCEPTS
AND TECHNIQUES DESCRIBED IN THIS BOOK, THE
AUTHOR HAS CREATED VARIOUS NAMES, COMPANY
NAMES, MAILING, E-MAIL AND INTERNET
ADDRESSES, PHONE AND FAX NUMBERS AND SIMILAR
process.
Our computer books use an integrated communication
process, which is very different from the approach used
in other computer books. Each spread is, in essence, a
flow chart — the text and screen shots are totally
incorporated into the layout of the spread. Introductory
text and helpful tips complete the learning experience.
maranGraphics’ approach encourages the left and right
sides of the brain to work together — resulting in faster
orientation and greater memory retention.
Above all, we are very proud of the handcrafted nature
of our books. Our carefully-chosen writers are experts
in their fields, and spend countless hours researching
and organizing the content for each topic. Our artists
rebuild every screen shot to provide the best clarity
possible, making our screen shots the most precise and
easiest to read in the industry. We strive for perfection,
and believe that the time spent handcrafting each
element results in the best computer books money
can buy.
Thank you for purchasing this book. We hope you
enjoy it!
Sincerely,
Robert Maran
President
maranGraphics
[email protected]
www.maran.com
www.hungryminds.com/visual
maranGraphics is a family-run business
Media Development Coordinator
Marisa E. Pearman
Production
Book Design
maranGraphics
®
Production Coordinator
Nancee Reeves
Layout
LeAndra Johnson, Adam Mancilla,
Kristin Pickett, Jill Piscitelli
Screen Artists
Ronda David-Burroughs,
David E. Gregory, Mark Harris,
Jill A. Proll
Cover Illustration
Russ Marini
Proofreader
Laura Albert, Laura L. Bowman,
John Greenough,
Andy Hollandbeck, Carl Pierce,
Dwight Ramsey
Indexer
TECHBOOKS Production Services
Special Help
Microsoft Corporation,
Richard Graves
CREDITS
ACKNOWLEDGMENTS
013601-X FM.F 10/18/01 11:56 AM Page v
Debra Raup, Ray Edmanson, Bob McCleary, Lawrence Anderson, Wolfgang Holma and Line 10
Production Team; the WinCC Team at Siemens that helped me in my transition to being a Microsoft
geek, including Emilio Matt, Rob Bohm, Bob Meads, Rich Miceli, Charlie Moore, Jörg Allmendinger, and
Rene Wolf; and my extended family and friends for the support in the things outside of work, including
Joe and Rosemarie Markiewicz, Robert and Donna Philips, Joe and Jan Markiewicz, and Chuck and
Mary Hanson, Rob and Gretchen Pfeiffer, and Reverend Joe Ciccone CSP.
A special thanks goes out to my brother, Danny Ryan. Without Danny, I would not have taken or
completed my contribution to this book or the ASP.NET book. Danny is an excellent partner and I look
forward to the great things that we will accomplish in our new endeavors.
ABOUT THE AUTHORS
AUTHORS’ ACKNOWLEDGMENTS
013601-X FM.F 10/18/01 11:56 AM Page vi
Eric Butow
To my grandmother, who instilled her Midwestern sensibilities in me.
Tommy Ryan
To my eternal partner, Linda.
013601-X FM.F 10/18/01 11:56 AM Page vii
viii
HOW TO USE THIS BOOK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xiv
1) GETTING STARTED WITH C#
Introduction to C# 2
Start Visual Studio .NET 4
Open a New C# Project 6
View .NET Framework Online Resources 8
Open a C# Web Project 10
Set JScript.NET as the Default Script Language 12
2) EXPLORING THE C# INTERFACE
Explore the Class View Window 14
View the Contents Window 16
Get Help Using the Index Window 18
Program Structs 80
Display Heap and Stack Information 84
5) WORKING WITH TYPES AND INTERFACES
Find Type Information 86
Program Constant Expressions 88
Specify Value Types 90
Program Numeric Types 92
Program the Boolean Type 96
Declare Reference Types 98
Enter Reference Type Declarations 100
Convert Value Types to Reference Types 104
Program Pointer Types 106
Insert The Void Type 108
Add Interface Properties 110
Add an Interface Index 112
6) PROGRAMMING METHODS AND EVENTS
View Information about Methods 116
Add a Method 118
Add Static Methods 122
Include Non-Static Methods 126
Enter Delegates 130
Program Events 132
Add an Event-Handling Method 134
ix
C#:
Your visual blueprint for
building .NET applications
013601-X FM.F 10/18/01 11:56 AM Page ix
x
7) USING ARRAYS
building .NET applications
9) ACCESSING PROPERTIES
View Information About Properties 184
Compare Properties and Indexers 186
Program Property Accessors 188
Declare Abstract Properties 192
Include Properties on Interfaces 194
10) BUILDING FORMS
View Information About Windows Forms 196
Add a Windows Form in the Windows Form Designer 198
Set the Form Type 200
Choose the Startup Windows Form 202
Create a Modal Form 204
Layout a Form 206
Set a Form Location 210
Change Form Properties 212
Create a Transparent Form 214
11) PROGRAMMING WEB APPLICATIONS
Introduction to Web Forms and Controls 216
Create an ASP.NET Web Site 218
Create a Web Form 220
Add Server Controls to a Web Form 222
Respond to an Event in Server-Side Controls 224
Read and Change Properties from Objects on a Web Form 226
Using Server-Side Components on Web Forms 228
013601-X FM.F 10/18/01 11:56 AM Page xi
xii
TABLE OF CONTENTS
12) ACCESSING DATA WITH C# AND ADO.NET
Introducing Data Access with ADO.NET 230
APPENDIX B) ABOUT THE CD-ROM
What’s on the CD-ROM 290
Using the E-Version of This Book 292
Hungry Minds, Inc. End-User License Agreement 294
INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .296
xiii
C#:
Your visual blueprint for
building .NET applications
013601-X FM.F 10/18/01 11:56 AM Page xiii
xiv
HOW TO USE THIS BOOK
C#: Your visual blueprint for building .NET applications
uses simple, straightforward examples to teach you
how to create powerful and dynamic programs.
To get the most out of this book, you should read
each chapter in order, from beginning to end. Each
chapter introduces new ideas and builds on the
knowledge learned in previous chapters. Once you
become familiar with C#: Your visual blueprint for
building .NET applications, this book can be used as
an informative desktop reference.
Who This Book Is For
If you are interested in writing programs for the new
Microsoft C# programming language, then C#: Your
visual blueprint for building .NET applications is the
book for you.
This book will take you through the basics of using
the Visual Studio Microsoft Development Environment
(MDE) window and familiarize you with the essentials
further. Apply It sections offer inside information and
pointers that can be used to enhance the functionality
of your code.
An Extra section provides additional information
about the task you just accomplished. Extra sections
often contain interesting tips and useful tricks to make
working with C# easier and more efficient.
013601-X FM.F 10/18/01 11:56 AM Page xiv
xv
The Organization Of This Book
C#: Your visual blueprint for building .NET applications
contains 15 chapters and two appendixes.
The first chapter, Getting Started with C#, introduces
you to C#, how to start Visual Studio .NET and open a
new C# project, how to learn about C# online and
how you can run C# with Web pages and Java.
Chapter 2, Exploring the C# Interface, shows you how
to navigate and work with the Visual Studio .NET MDE
window and receive online help. This chapter helps
you use the power of the MDE window to your
greatest advantage when you create C# programs.
Chapter 3, Working wiht Visual C# Basics, introduces
you to the essentials of C#. This chapter also covers
some C# programming fundamentals that enable you
to use the material in the following chapters to create
your own C# programs.
The fourth chapter, Programming C# Building Blocks,
gets you started with programming C# modules and
their two main building blocks, classes and structures.
Chapters 5 through 9 explore how you can add
sample code from each of the two-page lessons. This
saves you from having to type the code and helps you
quickly get started creating C# code. The CD-ROM
disc also contains several shareware and evaluation
versions of programs that can be used to work with
C#: Your visual blueprint for building .NET
applications. An e-version of the book is also available
on the disc.
C#:
Your visual blueprint for
building .NET applications
013601-X FM.F 10/18/01 11:56 AM Page xv
C
# is a new programming language created by
Microsoft and introduced with the release of Visual
Studio .NET (also known as Visual Studio .NET 7.0).
C# lets you write programs that enable you to manipulate
the computer to perform certain tasks.
C#
The Birth of C#
As a recent birth in the programming language family,
C# has two programming language parents: C++ and
Java. C# contains many C++ features but also adds the
object-oriented features from Java.
C# contains many different components, including:
• Versioning support, so that your base and derived
classes — templates that define how an object
performs — remain compatible as you develop them
• Events, so that your program can notify clients of a
class about something that has happened to an object
Integration
The primary advantage of using Visual Studio .NET is
that all of the programming languages have been
designed to work together from the start. When you
write a new C# program, Visual Studio .NET gives you
tools that you can use to program links from your C#
program into another program written in another Visual
Studio .NET language.
For example, you can create a database in Visual FoxPro
and then create a C# program that links into the Visual
FoxPro database. If you have written or acquired
completed programs in a Visual Studio language such as
Visual C++ or Visual Basic, you can include links from
your C# program into those programs. The end result is
seamless integrated functionality between programs.
Differences Between C# and C++
Microsoft includes Visual C++ and C# in Visual Studio
.NET. On the surface, C# has few differences from Visual
C++. When you look carefully and start programming,
you will notice that C# differs in several important
respects from Visual C++:
• C# has an alternate method of accessing the C++
initialization list when constructing the base class.
• A class can inherit implementation from only one
base class.
• You can call overridden base class members from
derived classes.
• C# has a different syntax for declaring C# arrays.
• There are differences in several different types
including bool, struct, and delegate.
for (int i = 1; i < 11; i++)
printf("%d\n", i);
Java:
for (int i = 1; i < 11; i++)
System.out.println("The number is " + i);
Assignments
C#: Visual C++: Java:
xValue=7; xValue=7; xValue=7;
WHILE Loops
C#:
while (x < 100);
x++;
Visual C++:
while (x < 100);
x++;
Java:
while (x < 100);
x++;
DLLs
The advent of Windows brought dynamic link libraries
(DLLs) to programmers. DLLs are small, independent
programs that contain executable routines that programs
can use to produce a certain result in Windows. For
example, if a program needs to open a file, you can
write your C# program that uses the code in the DLL to
open the file. Using DLLs frees up your time to work on
your program without having to reprogram the same
code in your C# program over and over again.
You can access DLLs from your C# program, and create
DLLs in C# for your C# program to refer to when necessary.
nTotal += nCount;
nCount++;
}
else {
nTotal += nCount;
nCount —;
};
Java:
if (nCount < nMax) {
nTotal += nCount;
nCount++;
}
else {
nTotal += nCount;
nCount —;
}
1
3
023601-X Ch01.F 10/18/01 11:57 AM Page 3
Programs
Microsoft Visual Studio.NET 7.0 Microsoft Visual Studio.NET 7.0
⁄ Click Start.
¤ Click Programs.
‹ Click Microsoft Visual
Studio .NET 7.0.
› Click Microsoft Visual
Studio .NET 7.0.
■ The Microsoft
Development Environment
window appears displaying
Visual Studio .NET also lets you create and change your
profile so that you can view windows, enter keyboard
commands, and receive help for the programming language
in which you are working. For example, if you have used an
older version of Visual Studio in the past and you prefer to
use the old windows and keyboard commands, Visual Studio
lets you use Visual Basic and C++ windows and menus.
START VISUAL STUDIO .NET
C#
4
START VISUAL STUDIO .NET
023601-X Ch01.F 10/18/01 11:57 AM Page 4
■ The Open Project window
appears so you can open an
existing C# project.
Á Click the New Project
button in step 5.
■ The New Project window
appears so you can open a
new C# project.
GETTING STARTED WITH C#
1
You can change what appears on the MDE when
you start up — it does not have to be the Start
page. You can start in an empty environment
without the Start page by clicking the My Profile
option and then clicking Show Empty
Environment from the At Startup drop-down
list box. The next time you start Visual Studio
.NET, the parent window will have nothing in
ˇ Click Browse to select a
location.
■ The Project Location
window appears listing the
project folders within your
My Projects folder.
Á Type the name of the
folder in which you want to
place the project.
‡ Click Open.
Visual C# Projects
Console
Applica
A
fter you start the MDE window, you can open a new
project. A project contains all the files related to your
C# program. After you determine the type of C#
program you want to write, Visual Studio creates all of the
project files you need to start programming. Visual Studio
contains project templates that let you create different
types of programs. The MDE window lets you create eight
different projects so you can tailor your C# program to the
needs of your program users.
You can create three different application types, each with a
different user interface. First, you can create a Windows
application that has a graphical, form-based interface. You
can create a console application with a character-based
interface. Finally, you can create a Web application that
resides on a Web server and uses Web pages for its
interface.
Note: If you know the name of the
path location where you want to
store the project, you can type it
directly into the Location field.
° Click OK.
■ The form or code that
corresponds to the template
you selected replaces the
Start Page in the parent
window.
GETTING STARTED WITH C#
1
When the Open Project window appears, it
shows all the projects in the default project
folder, My Projects. By clicking one of the icons
on the left side of the Project Location window,
you can choose the folder from which a project
is opened:
In the Project Location window, you can also select
any folder on your hard drive(s) by clicking the
Down Arrow ( ) next to the Look in field and then
selecting your drive. The folders on the selected
drive appear in the window.
You can view all the templates in the Templates area
by clicking the small button above and to the right
of the Templates area.
7
You can select from a folder that you
used recently by clicking the History
button.
The MDE window also contains links to help from both the
Microsoft Web site and online newsgroups where you can
leave and read messages from other C# programmers. You
can also search the Microsoft Web site for help with specific
topics.
Visual Studio .NET installs its self-contained help files when
you install Visual Studio .NET. You can access self-contained
help from the MDE menu bar, but you can only access
online help and resources from the Start menu. When you
access help on the Web or newsgroups, the MDE parent
window behaves as a window in your Internet browser
would, so you can get your help directly from the MDE
window without having to start an Internet browser.
If you have a continuous connection to the World Wide
Web, such as a DSL or cable modem connection, then the
Microsoft Web site help pages update automatically each
time you access them. If you have a dial-up connection and
you are not currently connected to the Web, then the MDE
window will require you to connect before you can view
the Microsoft Web site help pages.
VIEW .NET FRAMEWORK ONLINE RESOURCES
C#
8
VIEW .NET FRAMEWORK ONLINE RESOURCES
023601-X Ch01.F 10/18/01 11:57 AM Page 8
■ The Visual Studio .NET
Web site and available
newsgroups appear on the
page.
‹ Click the Headlines link. ■ A list of headlines with the
Web A
⁄ In the VS Start Page
window, click the New
Project button.
■ The New Project window
appears.
¤ Click the ASP.NET Web
Application icon to create a
Web application.
‹ Type the name of the Web
application to change it from
the Visual Studio .NET
default.
› Type the location for the
Web application.
■ If you do not have a Web
site, Visual Studio .NET
places the project in a Web
folder on your computer
called MOBILE_1.
ˇ Click OK.
C
# contains several templates for creating Web-based
projects so that you can integrate your C# programs
with a Web site and share the projects with other
members of a programming team. Sharing projects on a
Web site or a corporate intranet speeds development of
your C# program. Integrating a C# program with a Web site
lets you accept input from users on a Web site and
manipulate that data in the program.
1
When you create a new Web project and place it
on a Web directory, you should ensure that the
directory where you place your Web program is
secure so that only people with certain access
can view it. If the Web directory your program
resides in is not secure, others can access, alter,
and outright steal your code from both inside
and outside of your network. Discuss these
issues with your Webmaster before posting your
code on the Web or an intranet.
When you create a Web project, you must install
certain components onto your Web server. Without
these components, you cannot develop your Web
site. You can develop Web projects by installing the
following components onto your Web server:
Internet Information Server version 4.0 or later,
FrontPage Server Extensions, the .NET Framework
Common Language Runtime, and ASP.NET. Make
sure that your Webmaster has installed these
programs before you develop a C# Web application.
11
023601-X Ch01.F 10/18/01 11:57 AM Page 11