Explore 1.5M+ audiobooks & ebooks free for days

Only $12.99 CAD/month after trial. Cancel anytime.

Beginning Visual C# 2010
Beginning Visual C# 2010
Beginning Visual C# 2010
Ebook2,473 pages16 hours

Beginning Visual C# 2010

Rating: 0 out of 5 stars

()

Read preview

About this ebook

Update to Wrox's leading C# book for beginners

Get ready for the next release of Microsoft's C# programming language with this essential Wrox beginner's guide. Beginning Microsoft Visual C# 2010 starts with the basics and brings you thoroughly up to speed. You'll first cover the fundamentals such as variables, flow control, and object-oriented programming and gradually build your skills for Web and Windows programming, Windows forms, and data access.

Step-by-step directions walk you through processes and invite you to "Try it Out," at every stage. By the end, you'll be able to write useful programming code following the steps you've learned in this thorough, practical book.

  • The C# 4 programming language version will be synonymous with writing code with in C# 2010 in Visual Studio 2010, and you can use it to write Windows applications, Web apps with ASP.NET, and Windows Mobile and Embedded CE apps
  • Provides step-by-step instructions for mastering topics such as variables, flow controls, and object-oriented programming before moving to Web and Windows programming and data access
  • Addresses expressions, functions, debugging, error handling, classes, collections, comparisons, conversions, and more

If you've always wanted to master Visual C# programming, this book is the perfect one-stop resource.

Note: CD-ROM/DVD and other supplementary materials are not included as part of eBook file.

LanguageEnglish
PublisherWiley
Release dateFeb 8, 2011
ISBN9781118057193
Beginning Visual C# 2010

Read more from Karli Watson

Related to Beginning Visual C# 2010

Related ebooks

Programming For You

View More

Reviews for Beginning Visual C# 2010

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Beginning Visual C# 2010 - Karli Watson

    Title Page

    Beginning Visual C# 2010

    Published by

    Wiley Publishing, Inc.

    10475 Crosspoint Boulevard

    Indianapolis, IN 46256

    www.wiley.com

    Copyright © 2010 by Wiley Publishing, Inc., Indianapolis, Indiana

    Published simultaneously in Canada

    ISBN: 978-0-470-50226-6

    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) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions.

    Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or promotional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If professional assistance is required, the services of a competent professional person should be sought. Neither the publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site is referred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or Web site may provide or recommendations it may make. Further, readers should be aware that Internet Web sites listed in this work may have changed or disappeared between when this work was written and when it is read.

    For general information on our other products and services please contact our Customer Care Department within the United States at (877) 762-2974, outside the United States 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.

    Library of Congress Control Number: 2010920663

    Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Wrox Programmer to Programmer, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries, and may not be used without written permission. C# is a registered trademark of Microsoft Corporation in the United States and/or other countries. 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.

    for Donna

    —KARLI WATSON

    About the Authors

    KARLI WATSON is consultant at Infusion Development (www.infusion.com), a technology architect at Boost.net (www.boost.net), and a freelance IT specialist, author, and developer. For the most part, he immerses himself in .NET (in particular C# and lately WPF) and has written numerous books in the field for several publishers. He specializes in communicating complex ideas in a way that is accessible to anyone with a passion to learn, and spends much of his time playing with new technology to find new things to teach people about.

    During those (seemingly few) times where he isn't doing the above, Karli will probably be wishing he was hurtling down a mountain on a snowboard. Or possibly trying to get his novel published. Either way, you'll know him by his brightly colored clothes. You can also find him tweeting online at www.twitter.com/karlequin, and maybe one day he'll get around to making himself a website. Karli authored chapters 1 through 14, 21, 25 and 26.

    CHRISTIAN NAGEL is a Microsoft Regional Director and Microsoft MVP, an associate of Thinktecture, and owner of CN Innovation. He is a software architect and developer who offers training and consulting on how to develop Microsoft .NET solutions. He looks back on more than 25 years of software development experience. Christian started his computing career with PDP 11 and VAX/VMS systems, covering a variety of languages and platforms. Since 2000, when .NET was just a technology preview, he has been working with various .NET technologies to build numerous .NET solutions. With his profound knowledge of Microsoft technologies, he has written numerous .NET books, and is certified as a Microsoft Certified Trainer and Professional Developer. Christian speaks at international conferences such as TechEd and Tech Days, and started INETA Europe to support .NET user groups. You can contact Christian via his web sites, www.cninnovation.com and www.thinktecture.com and follow his tweets on www.twitter.com/christiannagel. Christian wrote chapters 17 through 20.

    JACOB HAMMER PEDERSEN is a Senior Application Developer at Elbek & Vejrup. He just about started programming when he was able to spell the word ‘BASIC', which, incidentally is the first programming language he ever used. He started programming the PC in the early '90s, using Pascal but soon changed his focus to C++, which still holds his interest. In the mid '90s his focus changed again, this time to Visual Basic. In the summer of 2000 he discovered C# and has been happily exploring it ever since. Primarily working on the Microsoft platforms, his other expertise includes MS Office development, SQL Server, COM and Visual Basic.Net.

    A Danish citizen, Jacob works and lives in Aarhus, Denmark. He authored chapters 15, 16, and 22.

    JON D. REID is a software engineering manager at Metrix LLC, an ISV of field service management software for the Microsoft environment. He has co-authored a variety .NET books, including Beginning Visual C# 2008, Beginning C# Databases: From Novice to Professional, Pro Visual Studio .NET, and many others. Jon wrote chapters 23 and 24.

    MORGAN SKINNER began his computing career at a young age on the Sinclair ZX80 at school, where he was underwhelmed by some code a teacher had written and so began programming in assembly language. Since then he's used all sorts of languages and platforms, including VAX Macro Assembler, Pascal, Modula2, Smalltalk, X86 assembly language, PowerBuilder, C/C++, VB, and currently C# (of course). He's been programming in .NET since the PDC release in 2000, and liked it so much he joined Microsoft in 2001. He now works in premier support for developers and spends most of his time assisting customers with C#. Morgan wrapped up the book by authoring chapter 27. You can reach Morgan at www.morganskinner.com.

    About the Technical Editor

    A blue-badge .NET architect and developer at Intel Corporation since March 2007, Doug Holland is part of the Visual Computing Group and is presently working within an advanced tools and development team with an emphasis on chipset and driver testing. Doug Holland holds a Master's Degree in Software Engineering from Oxford University and has been awarded both the Microsoft MVP and Intel Black Belt Developer awards. Outside of work, Doug enjoys spending time with his wife and four children; and is also an officer in the Civil Air Patrol/U.S. Air Force Auxiliary. Beyond architecting and developing software you can often find Doug at the local airport flying Cessnas over the California landscape.

    Credits

    Acquisitions Editor

    Paul Reese

    Development Editor

    Maryann Steinhart

    Project Editor

    Ami Frank Sullivan

    Technical Editor

    Doug Holland

    Production Editor

    Rebecca Anderson

    Copy Editor

    Luann Rouff

    Editorial Director

    Robyn B. Siesky

    Editorial Manager

    Mary Beth Wakefield

    Associate Director of Marketing

    David Mayhew

    Production Manager

    Tim Tate

    Vice President and Executive Group Publisher

    Richard Swadley

    Vice President and Executive Publisher

    Barry Pruett

    Associate Publisher

    Jim Minatel

    Project Coordinator, Cover

    Lynsey Stanford

    Proofreader

    Josh Chase, Word One

    Indexer

    J & J Indexing

    Cover Designer

    Michael E. Trent

    Cover Image

    © Lisa Loyd/istockphoto

    Acknowledgments

    FROM KARLI WATSON: Thanks to all at Wiley for their support and assistance on this project, as well as their understanding and flexibility in dealing with an author who never seems to have enough time to write. Special thanks to my editor for this book, Ami Sullivan, for adding sparkle and making this book shine. Also, thanks to friends, family, and work colleagues for understanding why I haven't have time for much socializing lately, and to Donna, as always, for all her support and for putting up with all the late nights.

    FROM CHRISTIAN NAGEL: To my two girls Angela and Stephanie. It's great to have you. Thanks for your great support and the big love you gave me during the hardest time of my life in 2009. Without you I couldn't have made it through. Stephanie, while not born yet, you were my biggest motivation during that time. I love you both!

    Also, a big thank you to my co-authors and the team at Wrox/Wiley for getting a great book out.

    Introduction

    C# is a relatively new language that was unveiled to the world when Microsoft announced the first version of its .NET Framework in July 2000. Since then its popularity has rocketed, and it has arguably become the language of choice for both Windows and Web developers who use the .NET Framework. Part of the appeal of C# comes from its clear syntax, which derives from C/C++ but simplifies some things that have previously discouraged some programmers. Despite this simplification, C# has retained the power of C++, and there is now no reason not to move into C#. The language is not difficult and it's a great one to learn elementary programming techniques with. This ease of learning, combined with the capabilities of the .NET Framework, make C# an excellent way to start your programming career.

    The latest release of C#, C# 4, which is included with version 4 of the .NET Framework, builds on the existing successes and adds even more attractive features. The latest release of Visual Studio (Visual Studio 2010), and the Express line of development tools (including Visual C# 2010 Express) also bring many tweaks and improvements to make your life easier and dramatically increase your productivity.

    This book is intended to teach you about all aspects of C# programming, from the language itself, through Windows and Web programming, to making use of data sources, and finally to some new and advanced techniques. You'll also learn about the capabilities of Visual C# 2010 Express, Visual Web Developer 2010 Express, and Visual Studio 2010, and all the ways that these products can aid your application development.

    The book is written in a friendly, mentor-style fashion, with each chapter building on previous ones, and every effort is made to ease you into advanced techniques painlessly. At no point will technical terms appear from nowhere to discourage you from continuing; every concept is introduced and discussed as required. Technical jargon is kept to a minimum; but where it is necessary, it too is properly defined and laid out in context.

    The authors of this book are all experts in their field, and are all enthusiastic in their passion for both the C# language and the .NET Framework. Nowhere will you find a group of people better qualified to take you under their collective wing and nurture your understanding of C# from first principles to advanced techniques. Along with the fundamental knowledge it provides, this book is packed full of helpful hints, tips, exercises, and full-fledged example code (available for download at p2p.wrox.com) that you will find yourself returning to repeatedly as your career progresses.

    We pass this knowledge on without begrudging it, and hope that you will be able to use it to become the best programmer you can be. Good luck, and all the best!

    Who This Book Is For

    This book is for everyone who wants to learn how to program in C# using the .NET Framework. The early chapters cover the language itself, assuming no prior programming experience. If you have programmed in other languages before, then much of the material in these chapters will be familiar. Many aspects of C# syntax are shared with other languages, and many structures are common to practically all programming languages (such as looping and branching structures). However, even if you are an experienced programmer you will benefit from looking through these chapters to learn the specifics of how these techniques apply to C#.

    If you are new to programming, you should start from the beginning. If you are new to the .NET Framework but know how to program, you should read Chapter 1 and then skim through the next few chapters before continuing with the application of the C# language. If you know how to program but haven't encountered an object-oriented programming language before, you should read the chapters from Chapter 8 onward.

    Alternatively, if you already know the C# language you may wish to concentrate on the chapters dealing with the most recent .NET Framework and C# language developments, specifically the chapters on collections, generics, and C# 4 language enhancements (Chapters 11 to 14), or skip the first section of the book completely and start with Chapter 15.

    The chapters in this book have been written with a dual purpose in mind: They can be read sequentially to provide a complete tutorial in the C# language, and they can be dipped into as required as reference material.

    In addition to the core material, starting with Chapter 3 each chapter also includes a selection of exercises at the end, which you can work through to ensure that you have understood the material. The exercises range from simple multiple choice or true/false questions to more complex exercises that require you to modify or build applications. The answers to all the exercises are provided as a download from the book's Web page at www.wrox.com.

    What's New in This Edition

    This book has been given plenty of love and attention to coincide with the release of C# 4 and .NET 4. Every chapter has been given an overhaul, with less relevant material removed, and new material added. All of the code has been tested against the latest version of the development tools used, and all of the screenshots have been retaken in Windows 7 to provide the most current windows and dialogs.

    Although we hate to admit our own fallibility, any errors from previous editions have been fixed, and many other reader comments have been addressed. Hopefully, we haven't introduced many new errors, but any that may have slipped through our web of experts will be corrected online as soon as we find them.

    New highlights of this edition include the following:

    Additional and improved code examples for you to try out

    Coverage of everything that's new in C# 4, from simple language improvements such as named and optional method parameters, to advanced techniques such as variance in generic types

    Streamlined coverage of advanced techniques to focus on those most appropriate to beginners without getting too obscure

    How This Book Is Structured

    This book is divided into six sections:

    Introduction: Purpose and general outline of the book's contents

    The C# Language: Covers all aspects of the C# language, from the fundamentals to object-oriented techniques

    Windows Programming: How to write Windows applications in C# and how to deploy them

    Web Programming: Web application development, Web services, and Web application deployment

    Data Access: How to use data in your applications, including data stored in files on your hard disk, data stored in XML format, and data in databases

    Additional Techniques: An examination of some extra ways to use C# and the .NET framework, including WPF, WCF, and WF—technologies introduced with .NET 3.0 and enhanced for .NET 4.

    The following sections describe the chapters in the five major parts of this book.

    The C# Language (Chapters 1–14)

    Chapter 1 introduces you to C# and how it fits into the .NET landscape. You'll learn the fundamentals of programming in this environment, and how Visual C# 2010 Express (VCE) and Visual Studio 2010 (VS) fit in.

    Chapter 2 starts you off with writing C# applications. You'll look at the syntax of C# and put the language to use with sample command-line and Windows applications. These examples will demonstrate just how quick and easy it can be to get up and running, and along the way you'll be introduced to the VCE and VS development environments and the basic windows and tools that you'll be using throughout the book.

    Next you'll learn more about the basics of the C# language. You'll learn what variables are and how to manipulate them in Chapter 3. You'll enhance the structure of your applications with flow control (looping and branching) in Chapter 4, and see some more advanced variable types such as arrays in Chapter 5. In Chapter 6 you'll start to encapsulate your code in the form of functions, which make it much easier to perform repetitive operations and make your code much more readable.

    By the beginning of Chapter 7 you'll have a handle on the fundamentals of the C# language, and will focus on debugging your applications. This involves looking at outputting trace information as your applications are executed, and at how VS can be used to trap errors and lead you to solutions for them with its powerful debugging environment.

    From Chapter 8 onward you'll learn about object-oriented programming (OOP), starting with a look at what this term means, and an answer to the eternal question What is an object? OOP can seem quite difficult at first. The whole of Chapter 8 is devoted to demystifying it and explaining what makes it so great, and you won't actually deal with much C# code until the very end of the chapter.

    Everything changes in Chapter 9, when you put theory into practice and start using OOP in your C# applications. This is where the true power of C# lies. You'll start by looking at how to define classes and interfaces, and then move on to class members (including fields, properties, and methods) in Chapter 10. At the end of that chapter you'll start to assemble a card game application, which is developed over several chapters, and will help to illustrate OOP.

    Once you've learned how OOP works in C#, Chapter 11 moves on to look at common OOP scenarios, including dealing with collections of objects, and comparing and converting objects. Chapter 12 takes a look at a very useful feature of C# that was introduced in .NET 2.0: generics, which enables you to create very flexible classes. Next, Chapter 13 continues the discussion of the C# language and OOP with some additional techniques, notably events, which become very important in, for example, Windows programming. Finally, Chapter 14 focuses on C# language features that were introduced with versions 3.0 and 4 of the language.

    Windows Programming (Chapters 15–17)

    Chapter 15 starts by introducing you to what is meant by Windows programming, and looks at how this is achieved in VCE and VS. Again, you'll start with the basics and build up your knowledge in both this chapter and Chapter 16, which demonstrates how you can use the wealth of controls supplied by the .NET Framework in your applications. You'll quickly understand how .NET enables you to build Windows applications in a graphical way, and assemble advanced applications with the minimum of effort and time.

    Chapter 17 discusses how to deploy your applications, including how to make installation programs that enable your users to get up and running with your applications in double-quick time.

    Web Programming (Chapters 18–20)

    This section is structured in a similar way to the Windows programming section. It starts with Chapter 18, which describes the controls that make up the simplest of Web applications, and how you can fit them together and make them perform tasks using ASP.NET. The chapter then moves on to look at more advanced techniques, ASP.NET AJAX, versatile controls, and state management in the context of the Web, as well as how to conform to Web standards.

    Chapter 19 is an excursion into the wonderful world of Web services, which provide programmatic access to information and capabilities across the Internet. Web services enable you to expose complex data and functionality to Web and Windows applications in a platform-independent way. This chapter discusses how to use and create Web services, and the additional tools that .NET provides, including security.

    Finally, Chapter 20 examines the deployment of Web applications and services, in particular the features of VS and VWD that enable you to publish applications to the Web with the click of a button.

    Data Access (Chapters 21–24)

    Chapter 21 looks at how your applications can save and retrieve data to disk, both as simple text files and as more complex representations of data. You'll also learn how to compress data, how to work with legacy data such as comma-separated value (CSV) files, and how to monitor and act on file system changes.

    In Chapter 22 you'll learn about the de facto standard for data exchange—namely, XML. By this point in the book, you'll have touched on XML several times in preceding chapters, but this chapter lays out the ground rules and shows you what all the excitement is about.

    The remainder of this part looks at LINQ, which is a query language built in to the latest versions of the .NET Framework. You start in Chapter 23 with a general introduction to LINQ, and then you will use LINQ to access a database and other data in Chapter 24.

    Additional Techniques (Chapters 25–27)

    Finally, in this part of the book you will look at some exciting new technologies that have emerged with the most recent .NET Framework releases. In Chapter 25 you will get to play with Windows Presentation Foundation (WPF) and see how it promises enormous changes to both Windows and Web development. Chapter 26 looks at Windows Communication Foundation (WCF), which extends and enhances the concept of Web services to an enterprise-level communication technology. The last chapter of the book, Chapter 27, looks at Windows Workflow Foundation (WF). WF enables you to implement workflow functionality in your applications, meaning you can define operations that are performed in a specific order controlled by external interactions, which is very useful for many types of applications.

    What You Need to Use This Book

    The code and descriptions of C# and the .NET Framework in this book apply to .NET 4. You don't need anything other than the Framework to understand this aspect of the book, but many of the examples require a development tool. This book uses Visual C# 2010 Express as its primary development tool, although some chapters use Visual Web Developer 2010 Express. In addition, some functionality is available only in Visual Studio 2010, which is noted where appropriate.

    Conventions

    To help you get the most from the text and keep track of what's happening, we've used a number of conventions throughout the book.

    warning

    Warning

    Boxes with this icon hold important, not-to-be forgotten information that is directly relevant to the surrounding text.

    note

    Note

    Notes, tips, hints, tricks, and asides to the current discussion are accompanied by this icon treatment.

    As for styles in the text:

    New terms and important words are italicized when introduced.

    Keyboard strokes are shown like this: Ctrl+A.

    Filenames, URLs, and code within the text looks like so: persistence.properties.

    Code is presented in two different ways:

    We use a monofont type with no highlighting for most code examples. We use bolded monofont to emphasize code that is of particular importance in the present context.

    Source Code

    As you work through the examples in this book, you may choose either to type in all the code manually or to use the source code files that accompany the book. All of the source code used in this book is available for download at www.wrox.com. Once at the site, simply locate the book's title (either by using the Search box or by using one of the title lists) and click the Download Code link on the book's detail page to obtain all the source code for the book.

    download

    Code snippets that are downloadable from wrox.com are easily identified with an icon; the filename of the code snippet follows in a code note that appears after the code, much like the one that follows this paragraph. If it is an entire code listing, the filename should appear in the listing title.

    Code snippet filename

    note

    Note

    Because many books have similar titles, you may find it easiest to search by ISBN; this book's ISBN is 978-0-470-50226-6.

    Once you download the code, just decompress it with your favorite compression tool. Alternately, you can go to the main Wrox code download page at www.wrox.com/dynamic/books/download.aspx to see the code available for this book and all other Wrox books.

    Errata

    Every effort is made to ensure that there are no errors in the text or in the code. However, no one is perfect, and mistakes do occur. If you find an error in one of our books, such as a spelling mistake or a faulty piece of code, your feedback is welcome. By sending in errata, you might save another reader hours of frustration, and at the same time you will help us provide even higher quality information.

    To find the errata page for this book, go to www.wrox.com and locate the title using the Search box or one of the title lists. Then, on the book details page, click the Book Errata link. On this page you can view all errata that has been submitted for this book and posted by Wrox editors. A complete book list, including links to each book's errata, is also available at www.wrox.com/misc-pages/booklist.shtml.

    If you don't spot your error on the Book Errata page, go to www.wrox.com/contact/techsupport.shtml and complete the form there to send us the error you have found. Once the information is checked, a message is posted to the book's errata page and the problem is fixed in subsequent editions of the book.

    p2p.wrox.com

    For author and peer discussion, join the P2P forums at p2p.wrox.com. The forums are a Web-based system for you to post messages relating to Wrox books and related technologies and to interact with other readers and technology users. The forums offer a subscription feature to e-mail you topics of interest of your choosing when new posts are made to the forums. Wrox authors, editors, other industry experts, and your fellow readers are present on these forums.

    At http://p2p.wrox.com you will find a number of different forums that will help you not only as you read this book, but also as you develop your own applications. To join the forums, just follow these steps:

    1. Go to p2p.wrox.com and click the Register link.

    2. Read the terms of use and click Agree.

    3. Complete the required information to join as well as any optional information you wish to provide and click Submit.

    4. You will receive an e-mail with information describing how to verify your account and complete the joining process.

    note

    Note

    You can read messages in the forums without joining P2P but in order to post your own messages, you must join.

    Once you join, you can post new messages and respond to messages other users post. You can read messages at any time on the Web. If you would like to have new messages from a particular forum e-mailed to you, click the Subscribe to this Forum icon by the forum name in the forum listing.

    For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to questions about how the forum software works as well as many common questions specific to P2P and Wrox books. To read the FAQs, click the FAQ link on any P2P page.

    Part I

    The C# Language

    Chapter 1: Introducing C#

    Chapter 2: Writing a C# Program

    Chapter 3: Variables and Expressions

    Chapter 4: Flow Control

    Chapter 5: More About Variables

    Chapter 6: Functions

    Chapter 7: Debugging and Error Handling

    Chapter 8: Introduction to Object-Oriented Programming

    Chapter 9: Defining Classes

    Chapter 10: Defining Class Members

    Chapter 11: Collections, Comparisons, and Conversions

    Chapter 12: Generics

    Chapter 13: Additional OOP Techniques

    Chapter 14: C# Language Enhancements

    Chapter 1

    Introducing C#

    What You Will Learn in this Chapter

    What the .NET Framework is and what it contains

    How .NET applications work

    What C# is and how it relates to the .NET Framework

    What tools are available for creating .NET applications with 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 2010 (VS) and Visual C# 2010 Express (VCE).

    What is the .NET Framework?

    The .NET Framework (now at version 4) is a 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 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. 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.

    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 enables the creation of Windows applications, Web applications, Web services, and pretty much anything else you can think of. Also, with Web applications it's worth noting that these are, by definition, multi-platform applications, since any system with a Web browser can access them. With the recent addition of Silverlight, this category also includes applications that run inside browsers on the client, as well as applications that merely render Web content in the form of HTML.

    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 an extremely high 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 use the .NET Framework throughout, and you'll make use of the additional tools in VS and VCE where necessary.

    In order 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, this is a two-stage process.

    CIL 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 Common Intermediate Language (CIL) code. This code isn't specific to any operating system (OS) 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 CIL 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 CIL code is compiled only 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. Typically, 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 CIL code, which is independent of the machine, operating system, and CPU. Several JIT compilers exist, each targeting a different architecture, and the appropriate one is 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.

    note

    Note

    You may come across references to Microsoft Intermediate Language (MSIL) or just IL. MSIL was the original name for CIL, and many developers still use this terminology.

    Assemblies

    When you compile an application, the CIL 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 CIL, 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 CIL, 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.

    Managed Code

    The role of the CLR doesn't end after you have compiled your code to CIL 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 periodically inspecting the memory of your computer 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).

    Figure 1.1

    1.1

    2. That code is compiled into CIL, which is stored in an assembly (see Figure 1.2).

    Figure 1.2

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

    Figure 1.3

    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.

    Figure 1.4

    1.4

    Linking

    Note one additional point concerning this process. The C# code that compiles into CIL 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. It is required 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 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 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. The C# language has been designed to incorporate 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 be carried out only by 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++. However, 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 is 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, or at least require unusual syntax. 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 additions 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:

    Windows applications: 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). Alternatively, you can use Windows Presentation Foundation (WPF) to build Windows applications, which gives you much greater flexibility and power.

    Web applications: Web pages such as those that might be viewed through any Web browser. The .NET Framework includes a powerful system for generating Web content dynamically, enabling 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. You can also write applications that run inside the browser with Silverlight.

    Web services: An 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 on which it resides. For more advanced capabilities, you can also create Windows Communication Foundation (WCF) services.

    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, through the ADO.NET Entity Framework, or through the 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 OOP until you've covered the basics. These are taught from first principles, assuming no programming knowledge at all.

    After that, you'll be ready to move on to developing more complex (but more useful) applications. Part II of this book looks at Windows Forms programming, Part III tackles Web application and Web service programming, Part IV examines data access (for database, file system, and XML data), and Part V covers some other .NET topics of interest.

    Visual Studio 2010

    In this book, you use the Visual Studio 2010 (VS) or Visual C# 2010 Express (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.

    VS includes designers for Windows Forms, Web Forms, and other 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 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 2010 Express Products

    In addition to Visual Studio 2010, Microsoft also supplies several simpler development tools known as Visual Studio 2010 Express Products. These are freely available at http://www.microsoft.com/express.

    Two of these products, Visual C# 2010 Express and Visual Web Developer 2010 Express, 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 the chapters.

    In this book you'll use VCE to develop C# applications wherever possible, and only use VS where it is necessary for certain functionality. Of course, if you have VS there is no need to use an express product.

    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.

    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.

    Summary

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

    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 2010 and Visual C# 2010 Express.

    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.

    What You Learned in this Chapter

    genuf001

    Chapter 2

    Writing a C# Program

    What You Will Learn in this Chapter

    A basic working knowledge of Visual Studio 2010 and Visual C# 2010 Express Edition

    How to write a simple console application

    How to write a Windows Forms application

    Now that you've spent some time learning what C# is and how it fits into the .NET Framework, it's time to get your hands dirty and write some code. You use Visual Studio 2010 (VS) and Visual C# 2010 Express (VCE) throughout this book, so the first thing to do is have a look at some of the basics of these development environments.

    VS is an enormous and complicated product, and it can be daunting to first-time users, but using it to create basic applications can be surprisingly simple. As you start to use VS in this chapter, you will see that you don't need to know a huge amount about it to begin playing with C# code. Later in the book you'll see some of the more complicated operations that VS can perform, but for now a basic working knowledge is all that is required.

    VCE is far simpler for getting started, and in the early stages of this book all the examples are described in the context of this IDE. However, if you prefer, you can use VS instead, and everything will work in more or less the same way. For that reason, you'll see both IDEs in this chapter, starting with VS.

    After you've had a look at the IDEs, you put together two simple applications. You don't need to worry too much about the code in these for now; you just prove that things work. By working through the application creation procedures in these early examples, they will become second nature before too long.

    The first application you create is a simple console application. Console applications are those that don't make use of the graphical windows environment, so you won't have to worry about buttons, menus, interaction with the mouse pointer, and so on. Instead, you run the application in a command prompt window and interact with it in a much simpler way.

    The second application is a Windows Forms application. The look and feel of this is very familiar to Windows users, and (surprisingly) the application doesn't require much more effort to create. However, the syntax of the code required is more complicated, even though in many cases you don't actually have to worry about details.

    You use both types of application over the next two parts of the book, with slightly more emphasis on console applications at the beginning. The additional flexibility of Windows applications isn't necessary when you are learning the C# language, while the simplicity of console applications enables you to concentrate on learning the syntax and not worry about the look and feel of the application.

    The Development Environments

    This section explores the VS and VCE development environments, starting with VS. These environments are similar, and you should read both sections regardless of which IDE you are using.

    Visual Studio 2010

    When VS is first loaded, it immediately presents you with a host of windows, most of which are empty, along with an array of menu items and toolbar icons. You will be using most of these in the course of this book, and you can rest assured that they will look far more familiar before too long.

    If this is the first time you have run VS, you will be presented with a list of preferences intended for users who have experience with previous releases of this development environment. The choices you make here affect a number of things, such as the layout of windows, the way that console windows run, and so on. Therefore, choose Visual C# Development Settings; otherwise, you may find that things don't quite work as described in this book. Note that the options available vary depending on the options you chose when installing VS, but as long as you chose to install C# this option will be available.

    If this isn't the first time that you've run VS, but you chose a different option the first time, don't panic. To reset the settings to Visual C# Development Settings you simply have to import them. To do this, select Tools ⇒ Import and Export Settings, and choose the Reset All Settings option, shown in Figure 2.1.

    Figure 2.1

    2.1

    Click Next, and indicate whether you want to save your existing settings before proceeding. If you have customized things, you might want to do this; otherwise, select No and click Next again. From the next dialog, select Visual C# Development Settings, shown in Figure 2.2. Again, the available options may vary.

    Figure 2.2

    2.2

    Finally, click Finish to apply the settings.

    The VS environment layout is completely customizable, but the default is fine here. With C# Developer Settings selected, it is arranged as shown in Figure 2.3.

    Figure 2.3

    2.3

    The main window, which contains a helpful Start Page by default when VS is started, is where all your code is displayed. This window can contain many documents, each indicated by a tab, so you can easily switch between several files by clicking their filenames. It also has other functions: It can display GUIs that you are designing for your projects, plain-text files, HTML, and various tools that are built into VS. You will come across all of these in the course of this book.

    Above the main window are toolbars and the VS menu. Several different toolbars can be placed here, with functionality ranging from saving and loading files to building and running projects to debugging controls. Again, you are introduced to these as you need to use them.

    Here are brief descriptions of each of the main features that you will use the most:

    The Toolbox toolbar pops up when the mouse moves over it. It provides access to, among other things, the user interface building blocks for Windows applications. Another tab, Server Explorer, can also appear here (selectable via the View Server Explorer menu option) and includes various additional capabilities, such as providing access to data sources, server settings, services, and more.

    The Solution Explorer window displays information about the currently loaded solution. A solution, as you learned in the previous chapter, is VS terminology for one or more projects along with their configurations. The Solution Explorer window displays various views of the projects in a solution, such as what files

    Enjoying the preview?
    Page 1 of 1