C# Bible Jeff Ferguson, Brian Patterson, Jason Beres, Pierre Boutquin, and Meeta Gupta Published by Wiley Publishing, Inc. 10475 Crosspoint Boulevard Indianapolis,_IN 46256 www.wiley.com Copyright © 2002 by Wiley Publishing, Inc., Indianapolis, Indiana Published simultaneously in Canada Library of Congress Control Number: 2001092884 ISBN: 0-7645-4834-4 Manufactured in the United States of America 10 9 8 7 6 5 4 3 2 1 1B/ST/QX/QS/IN No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 750-4744. Requests to the Publisher for permission should be addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4447, E-Mail: [email protected]. LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: WHILE THE PUBLISHER AND AUTHOR HAVE USED THEIR BEST EFFORTS IN PREPARING THIS BOOK, THEY MAKE NO 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. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES REPRESENTATIVES OR WRITTEN SALES MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR YOUR SITUATION. YOU SHOULD CONSULT WITH A PROFESSIONAL WHERE APPROPRIATE. 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. For general information on our other products and services or to obtain technical support, please contact our Customer Care Department within the U.S. at 800-762-2974, outside the U.S. at (317) 572-3993 or fax (317) 572-4002. Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books. Trademarks: Wiley, the Wiley Publishing logo and related trade dress are trademarks or registered trademarks of Wiley Publishing, Inc., in the United States and other countries, and may not be used without written permission. All other trademarks are the property of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book. About the Authors Jeff Ferguson is a senior consultant with Magenic Technologies, a software consulting company dedicated to solving business problems exclusively using Microsoft tools and technologies. He has been a professional software developer since 1989 and has developed software using C, C++, and C# for Unix, DOS, and Windows systems. Send e-mail to Jeff at [email protected] (remember to include all three "F"s in the name portion of the address). Brian Patterson currently works for Affina, Inc., as a Technical Team Leader, where he is generally working with C++ on HP-UX or Windows development with any number of the Visual Studio languages. Brian has been writing for various Visual Basic publications since 1994 and has co-written several .NET-related books, including Migrating to Visual Basic .NET and .NET Enterprise Development with VB.NET. You can generally find him posting in the MSDN newsgroups or you can reach him by e-mail at [email protected]. Jason Beres has been a software developer for 10 years. He is currently a consultant in south Florida and works exclusively with Microsoft technologies. Jason holds the MCT, MCSD, and MCDBA certifications from Microsoft. When he is not teaching, consulting, or writing, he is formatting his hard drive, installing the latest beta products from Microsoft, and keeping up with the latest episodes of "Star Trek." Pierre Boutquin is a senior software architect in the treasury of a major Canadian bank, where he helps develop leading-edge market risk management software. He has more than a decade of experience implementing PC-based computer systems, with in-depth knowledge of distributed systems design, data warehousing, Visual Basic, Visual C++, and SQL. He has co- written many programming books and has contributed material on VB, COM+, XML, and SQL to other books. Koshka and Sasha, his two adorable Burmese cats, own most of Pierre's spare time. While petting them, he often thinks how nice it would be to find more time and get back into chess or keep up with news from Belgium, his native country. You can reach him at [email protected]. Meeta Gupta has a master's degree in computer engineering. Networking is her first love. She is presently working at NIIT Ltd., where she designs, develops, and authors books on a varied range of subjects. She has co-written books on TCP/IP, A+ Certification, ASP.NET, and PHP. She also has an extensive experience in designing and developing ILTs. Besides writing, Meeta has conducted courses on C++, Sybase, Windows NT, Unix, and HTML for a diverse audience, from students to corporate clients. NIIT is a global IT solutions company that creates customized multimedia training products and has more than 2,000 training centers worldwide. NIIT has more than 4,000 employees in 37 countries and has strategic partnerships with a number of major corporations, including Microsoft and AT&T. About the Series Editor Michael Lane Thomas is an active development community and computer industry analyst who presently spends a great deal of time spreading the gospel of Microsoft .NET in his current role as a .NET technology evangelist for Microsoft. In working with over a half-dozen publishing companies, Michael has written numerous technical articles and written or contributed to almost 20 books on numerous technical topics, including Visual Basic, Visual C++, and .NET technologies. He is a prolific supporter of the Microsoft certification programs, having earned his MCSD, MCSE+I, MCT, MCP+SB, and MCDBA. In addition to technical writing, Michael can also be heard over the airwaves from time to time, including two weekly radio programs on Entercom (http://www.entercom.com/) stations, including most often in Kansas City on News Radio 980KMBZ (http://www.kmbz.com/). He can also occasionally be caught on the Internet doing an MSDN Webcast (http://www.microsoft.com/usa/webcasts/) discussing .NET, the next generation of Web application technologies. Michael started his journey through the technical ranks back in college at the University of Kansas, where he earned his stripes and a couple of degrees. After a brief stint as a technical and business consultant to Tokyo-based Global Online Japan, he returned to the States to climb the corporate ladder. He has held assorted roles, including those of IT manager, field engineer, trainer, independent consultant, and even a brief stint as Interim CTO of a successful dot-com, although he believes his current role as .NET evangelist for Microsoft is the best of the lot. He can be reached via e-mail at [email protected]. Credits Senior Acquisitions Editor Sharon Cox Project Editor Eric Newman Development Editor Sydney Jones Copy Editor Luann Rouff Technical Editor Sundar Rajan Editorial Manager Mary Beth Wakefield Vice President & Executive Group Publisher Richard Swadley Vice President and Publisher Joseph B. Wikert Project Coordinator Ryan T. Steffen Graphics and Production Specialists Beth Brooks, Melanie DesJardins, Joyce Haughey, Barry Offringa, Laurie Petrone, Betty Schulte, Jeremey Unger Quality Control Technicians Laura Albert, Susan Moritz Proofreading and Indexing TECHBOOKS Production Services For my family and my friends. Jeff Ferguson This book is dedicated to my uncle, Brian Weston, who didn't seem to mind when I came to visit and spent all day with his TRS-80 Model II. Brian Patterson To Nitin, who was the driving force. Meeta Gupta Preface Microsoft's .NET Framework represents the most significant change in software development methodology for a Microsoft operating system since the introduction of Windows. It is built using an architecture that allows software languages to work together, sharing resources and code, to provide developers with the advanced tools necessary to build the next generation of desktop and Internet-enabled applications. Microsoft's Visual Studio .NET product includes new versions of their Visual Basic and C++ compiler products that target .NET development, as well as a brand new language called C# (pronounced "C-sharp"). C# Bible will show you how to write code using this brand new language. Language constructs such as statements, variables, control loops, and classes are all covered. In addition, the book will show you how to apply C# to programming tasks that developers often face in the real world. The final portions of the book will show you how to use C# to develop Web sites, access databases, work with legacy COM and COM+ objects, develop Windows desktop applications, work with various .NET Framework concepts, and more. The primary focus of this book is .NET development using C# as the implementation language and the .NET Framework's C# command-line compiler as the primary development tool. C# development using the Visual Studio .NET tool is not covered in this book, although the task of using Visual Studio .NET to develop C# applications can be easily mastered once the fundamentals of .NET development using C# are well understood. Who Should Read This Book This book was written with both the novice and experienced developer in mind. If you know nothing at all about the basics of software development, this book will get you started with the fundamentals, teaching you how variables, control loops, and classes work. The book will also speak to developers of any skill level, showing you the .NET tools available for C# development and providing you with tips to make your own C# applications work seamlessly within the .NET Framework development guidelines. If you already have delved into the world of creating .NET applications, you will find this book a useful resource, because it covers almost every aspect of .NET development in depth. The first three parts of the book serve as an illustrative reference to using features of the C# language. By contrast, the final two portions of the book are dedicated to showcasing C# as an application development platform, illustrating the role of C# in desktop-, Web-, database-, and component-based applications. This book assumes that you are seeing C# for the very first time and aims to provide an understanding of the language without requiring any previous language expertise. The book does assume, however, that you are familiar with the application environments used in conjunction with your C# applications. The final portions of this book cover the use of C# with desktop, Web, database and component applications, but does not explain those platforms in detail. Rather, the book assumes that you have a working knowledge of those application platforms. How This Book Is Organized This book is organized into five parts, plus an appendix. Part I: C# Language Fundamentals This first part of the book provides a brief overview of the C family of programming languages and moves to discuss basic syntax issues with C#. Variables, statements, flow control loops, and method calls are all discussed. First-time developers will also find a discussion of the usage of these syntax elements and will be able to understand how to build code using these constructs. Part II: Object-Oriented Programming with C# The chapters in Part II cover the notion of a class in C#. The class is the fundamental unit of code in a C# application, and understanding classes is key to the construction of a working C# application. Part II covers topics such as class design, base classes, derived classes, and operator overloading. Part III: Advanced C# The third part of the book focuses on specific language features employed by more advanced C# applications. Topics such as exception handling, interface implementation, namespaces, attributes, and unsafe code are all covered. The final chapter in Part III is devoted to presenting some tough programming problems and solutions implemented using C#. Part IV: Developing .NET Solutions Using C# Part IV shows how to use C# in applications that make use of various parts of the .NET Framework. This part of the book is a departure from the other sections, which are devoted to presenting the language features of C#. Part IV uses C# to build applications using a variety of .NET application platforms, from Windows forms to Web Forms to ASP.NET applications and database access. We will also take a look at working with some advanced .NET technologies using C#, including threading, assemblies, and reflection. Part V: C# and the .NET Framework The final part of the book describes how C# can be used to work with the .NET Framework itself. Framework concepts such as assemblies, reflection, threading, and COM/COM+ component interoperability are explained. Each chapter explains the appropriate Framework concept and also shows how to take advantage of the technology using C# as the implementation language. Appendix The final section of the book is devoted to an appendix, "XML Primer," which provides an overview of the eXtensible Markup Language (XML). It provides an overview of the history of XML and how developers can take advantage of XML to describe data in a standardized way. Many .NET projects make use of XML in one form or another, and several .NET configuration files are based on the XML infrastructure. Companion Web site This book provides a companion Web site from which you can download the code from various chapters. All the code listings reside in a single WinZip file that you can download by going to www.wiley.com/extras and selecting the C# Bible link. After you download the file, and if you have WinZip already on your system, you can open it and extract the contents by double-clicking. If you don't currently have WinZip, you can download an evaluation version from www.winzip.com. How to Approach This Book Readers who are completely new to software development (readers coming from a Webmaster background, perhaps) will get the most benefit from this book by first reading Parts I and II to get a good handle on how the mechanics of a software application work. It will be important for new developers to understand the basics of software development and how all of the pieces fit together to construct a complete C# application. Readers approaching C# with a background in C++ will find C# very familiar. C# was built with C and C++ in mind, and the syntax resembles that of these older languages. These readers might wish to skim through Parts I and II to get a feel for the variance in syntax, and then might want to dive right in to Part III to understand the advanced features of the language. Many of the topics in Part III delve into concepts that distinguish C# from its predecessors. Developers already familiar with C# will also find useful material. Parts IV and V showcase the use of C# in a variety of .NET platform applications and present several examples that illustrate C# code that can be used to perform a variety of tasks. These final two parts move the book from a theoretical language level to a practical level and are ideal for developers of any level wishing to understand how C# can be used to implement a variety of applications. Conventions Used in This Book Each chapter in this book begins with a heads-up of the topics covered in the chapter and ends with a summary of what you should have learned by reading the chapter. Throughout this book, you will find icons in the margins that highlight special or important information. Keep an eye out for the following icons: Caution A Caution icon indicates a procedure that could potentially cause difficulty or even data loss; pay careful attention to Caution icons to avoid common and not-so- common programming pitfalls. Cross-Reference Cross-Reference icons point to additional information about a topic, which you can find in other sections of the book. Note A Note icon highlights interesting or supplementary information and often contains extra bits of technical information about a subject. Tip Tip icons draw attention to handy suggestions, helpful hints, and useful pieces of advice. In addition to the icons listed previously, the following typographical conventions are used throughout the book: • Code examples appear in a fixed width font. • Other code elements, such as data structures and variable names, appear in fixed width. • File names and World Wide Web addresses (URLs) also appear in fixed width. • The first occurrence of an important term in a chapter is highlighted with italic text. Italic is also used for placeholders — for example, ICON <icon file name>, where <icon file name> represents the name of a bitmap file. • Menu commands are indicated in hierarchical order, with each menu command separated by an arrow. For example, File → Open means to click the File command on the menu bar, and then select Open. • Keyboard shortcuts are indicated with the following syntax: Ctrl+C. What Is a Sidebar? Topics in sidebars provide additional information. Sidebar text contains discussion that is related to the main text of a chapter, but not vital to understanding the main text. Acknowledgments Jeff Ferguson: Few books of this size and scope are ever the work of a single individual, and this one is no exception. I owe a debt of gratitude to many people for their help and encouragement in writing this book. First, I must thank my parents for the upbringing that I received. Without their parental guidance, I would not have turned out to be the person I am today and would not have been able to complete tasks of any size. I am always grateful not only to you but also to the entire family for the love and support I always receive. I would like to thank everyone at Wiley for their leadership in the production of this material. Thank you, Andrea Boucher, Sharon Cox, Eric Newman, and Chris Webb, for leading me through the daunting world of technical book publishing. Thanks also go to Rolf Crozier, who initially discussed this project with me in the early days. I owe a special thank you to my colleague Bob Knutson, who reviewed drafts of the material in this book. Thanks go to Greg Frankenfield and Paul Fridman for creating a top-notch Microsoft-based consulting organization that allows me to work on client projects as well as my own. The technical growth I have experienced throughout my time at Magenic has been immeasurable. Here's to Magenic's continued success. Thanks to everyone on the DOTNET mailing lists and newsgroups on the Internet. I am learning a tremendous amount about the .NET Framework and C# simply by reading your posts. The banter sent back and forth has given me a better understanding of how all of these new pieces fit together. Brian Patterson: I'd like to thank my wife, Aimee, for allowing me the many hours hidden away in the computer so I could complete my work on this book. A special thanks to Steve Cisco for the hard work he put into this book, which led the way for the rest of us; to Sharon Cox, the acquisitions editor, who constantly kept me on track; to the project editor, Eric Newman, for keeping all my ducks in a row; and to the series editor, Michael Lane Thomas, who reviewed each and every chapter, making some very good suggestions and providing some valuable insight into Microsoft and the .NET framework. Pierre Boutquin: Much hard work goes into the creation of a book, and not just from the people mentioned on the cover. I must especially thank the Wiley team for their tremendous dedication to produce a quality book. The reviewers deserve a lot of credit for making me look like an accomplished writer. Finally, this effort would not have been possible without the support from my family and friends: Sandra, Andrea, Jennifer and Paul, Tindy and Doel, Marcel and Diana Ban, Margaret Fekete, and John and Nadine Marshall. Meeta Gupta: I thank Anita for giving me the opportunity. However, my biggest thanks go to Nitin for, well, everything. Part I: C# Language Fundamentals Chapter List Chapter 1: An Introduction to C# Chapter 2: Writing Your First C# Program Chapter 3: Working with Variables Chapter 4: Expressions Chapter 5: Controlling the Flow of Your Code Chapter 6: Working with Methods Chapter 7: Grouping Data Using Structures Chapter 1: An Introduction to C# In This Chapter For the past 20 years, C and C++ have been the languages of choice for commercial and critical business applications. These languages provided a severe degree of control to the developer by letting them use pointers and many low-level system functions. However, when you compare languages. such as Microsoft Visual Basic to C/C++, you come to realize that while C and C++ are much more powerful languages, it takes a great deal longer to develop applications. Many C/C++ programmers have dreaded the notion of switching to languages such as Visual Basic because they would lose much of the low level control they are used to. What the developer community needed was a language that fell somewhere in between these two. A language that would help with rapid application development but would also allow for a great deal of control and a language that would integrate well with Web-application development, XML, and many of the emerging technologies.