C# 2008 For Dummies®


by Chuck Sphar and Stephen Randy Davis




About the Authors

Stephen R. Davis, who goes by the name of Randy, lives with his wife and son near Dallas, Texas. He and his family have written numerous books, including C++ For Dummies and C++ Weekend Crash Course. Stephen works for L-3 Communications.

Chuck Sphar escaped Microsoft’s C++ documentation camps in 1997, after six years’ hard labor as a senior technical writer. He’s perpetrated three previous tomes, one on object-oriented programming for the Mac, one on Microsoft’s MFC class library, and C# 2005 For Dummies, a revision of Randy’s original edition. He’s currently finishing a novel about ancient Rome (againstrome.com) and gobbling great mouthfuls of .NET programming. Chuck can be reached for praise and minor nits at chuck@csharp102.info.



For a remarkable woman and great friend, Helen Tross — and, of course, as always, my Pam — Chuck Sphar


Authors’ Acknowledgments

As always, thanks to my agent, Claudette Moore, who brought the book to me in 2005. I also want to thank Randy Davis for being willing to hand over his baby to a guy he didn’t know. I’d have found that very hard, and I hope I’ve done justice in two revisions of his original edition.

Many thanks are due as well to the fine folks at Wiley, starting with Acquisitions Editor Katie Feltman and Project Editor Pat O’Brien. I’d also like to thank Barry Childs-Helton for much of the book’s consistency, and the art, media, technical, and other production folks who turn my files into a real book.

The most heartfelt thanks are due to Pam for constant encouragement and much enabling. She’s my partner in all things. — Chuck Sphar


Publisher’s Acknowledgments

We’re proud of this book; please send us your comments through our online registration form located at www.dummies.com/register/.

Some of the people who helped bring this book to market include the following:

Acquisitions, Editorial, and Media Development

Project Editor: Pat O’Brien

Acquisitions Editor: Katie Feltman

Senior Copy Editor: Barry Childs-Helton

Technical Editor: Roy El-Rayes

Editorial Manager: Kevin Kirschner

Media Development Manager: Laura VanWinkle

Editorial Assistant: Amanda Foxworth

Sr. Editorial Assistant: Cherie Case

Cartoons: Rich Tennant (www.the5thwave.com)

Composition Services

Project Coordinator: Kristie Rees

Layout and Graphics: Stacie Brooks, Carl Byers, Reuben W. Davis, Shane Johnson, Christine Williams

Proofreader: Christine Sabooni

Indexer: Potomac Indexing, LLC

Publishing and Editorial for Technology Dummies

Richard Swadley, Vice President and Executive Group Publisher

Andy Cummings, Vice President and Publisher

Mary Bednarek, Executive Acquisitions Director

Mary C. Corder, Editorial Director

Publishing for Consumer Dummies

Diane Graves Steele, Vice President and Publisher

Joyce Pepple, Acquisitions Director

Composition Services

Gerry Fahey, Vice President of Production Services

Debbie Stailey, Director of Composition Services




What’s New in C# 3.0

About This Book

What You Need to Use the Book

How to Use This Book

How This Book Is Organized

Icons Used in This Book

Conventions Used in This Book

Where’s the Code? And the Bonus Goodies?

Where to Go from Here

Part I : Getting Started with C#

Chapter 1: Creating Your First C# Console Application

Getting a Handle on Computer Languages, C#, and .NET

Creating Your First Console Application

Making Your Console App Do Something

Reviewing Your Console Application

Introducing the Toolbox Trick

Part II : Basic C# Programming

Chapter 2: Living with Variability — Declaring Value-Type Variables

Declaring a Variable

What’s an int?

Representing Fractions

Handling Floating-Point Variables

Using the Decimal Type — Is It an Integer or a Float?

Examining the bool Type — Is It Logical?

Checking Out Character Types

What’s a Value-Type?

Comparing string and char

Is This a Leap Year? — DateTime

Declaring Numeric Constants

Changing Types — The Cast

New Feature: Letting the C# Compiler Infer Data Types

Chapter 3: Smooth Operators

Performing Arithmetic

Performing Logical Comparisons — Is That Logical?

Matching Expression Types at TrackDownAMate.com

Chapter 4: Getting into the Program Flow

Branching Out with if and switch

Here We Go Loop the Loop

Looping a Specified Number of Times with for

Nesting Loops

Don’t goto Pieces

Chapter 5: Lining Up Your Ducks with Collections

The C# Array

A Loop Made foreach Array

Sorting Through Arrays of Data

New Feature — Using var for Arrays

Loosening Up with C# Collections

Understanding Collection Syntax

Using Lists

Using Dictionaries

New Feature — Array and Collection Initializers

New Feature — Using Sets

On Not Using Old-Fashioned Collections

Chapter 6: Pulling Strings

The Union Is Indivisible, and So Are Strings

Performing Common Operations on a String

Comparing Strings

What If I Want to Switch Case?

Looping Through a String

Searching Strings

Getting Input from the Command Line

Controlling Output Manually

Formatting Your Strings Precisely

StringBuilder: Manipulating Strings More Efficiently

Part III : Using Objects

Chapter 8: We Have Our Methods

Defining and Using a Method

An Example Method for Your Files

Having Arguments with Methods

Passing Value-Type and Reference-Type Arguments

Returning Values after Christmas

Chapter 9: Let Me Say This about this

Passing an Object to a Method

Defining Methods

Accessing the Current Object

New Feature: Extension Methods

Chapter 10: Object-Oriented Programming — What’s It All About?

Object-Oriented Concept #1 — Abstraction

Object-Oriented Concept #2 — Classification

Why Classify?

Object-Oriented Concept #3 — Usable Interfaces

Object-Oriented Concept #4 — Access Control

How Does C# Support Object-Oriented Concepts?

Part IV : Object-Oriented Programming

Chapter 11: Holding a Class Responsible

Restricting Access to Class Members

Why Worry about Access Control?

Defining Class Properties

Getting Your Objects Off to a Good Start — Constructors

The C#-Provided Constructor

Replacing the Default Constructor

Overloading the Constructor (Is That Like Overtaxing a Carpenter?)

Avoiding Duplication among Constructors

Being Object-Stingy

Chapter 12: Inheritance — Is That All I Get?

Inheriting a Class

Why Do You Need Inheritance?

A More Involved Example — Inheriting from a BankAccount Class

IS_A versus HAS_A — I’m So Confused

When to IS_A and When to HAS_A?

Other Features That Support Inheritance

The object Class

Inheritance and the Constructor

The Updated BankAccount Class

Chapter 13: Poly-what-ism?

Overloading an Inherited Method


The Class Business Card: ToString()

C# During Its Abstract Period

Sealing a Class

Chapter 14: Interfacing with the Interface


What Is an Interface?

Using an Interface

Using C#’s Predefined Interface Types

Can I See a Program That CAN_ BE_USED_AS an Example?

Unifying Class Hierarchies

Hiding Behind an Interface

Inheriting an Interface

Using Interfaces to Manage Change in Object-Oriented Programs

Part V : Now Showing in C# 3.0

Chapter 15: Delegating Those Important Events

E.T. Phone Home — The Callback Problem

What’s a Delegate?

Pass Me the Code, Please — Examples

How About a More Real-World Example?

Shh! Keep It Quiet — Anonymous Methods

Stuff Happens — C# Events

Chapter 16: Mary Had a Little Lambda Expression

Collections and the Do-to-Each Problem

New Feature: Using Lambda Expressions

Using Lambda Expressions for Any Delegate

Chapter 17: LINQing Up with Query Expressions

Reviewing the C# 3.0 Features

What’s a Query, and Why Should I Care?

Querying in C# 3.0

What Can I Do with a Query?

Filtering Out the Espresso Grounds

Selecting and Grouping What You Want

Sorting the Stuff You Select

Is There Any Method to Querying?

Counting, Summing, Averaging, and Stuff Like That

Treating an Object Like a Collection

Part VI : The Part of Tens

Chapter 18: Ten Common Build Errors (And How to Fix Them)

: Further Reading


This edition of C# 2008 for Dummies represents a pretty thorough over-haul. It adds tons of new material, an improved organization, and many new example programs. So even if you’ve seen the book before, it’s worth another look.

The C# programming language is a powerful and, at some six years old, relatively mature descendant of the earlier C, C++, and Java languages. Program-ming with it is a lot of fun, as you’re about to find out in this book.

Microsoft created C# as a major part of its .NET initiative. Microsoft turned the specifications for the C# language over to the ECMA (pronounced ek-ma) international standards committee in the summer of 2000, so that, in theory, any company can come up with its own version of C# written to run on any operating system, on any machine larger than a calculator.

When the first edition of this book came out, Microsoft’s C# compiler was the only game in town, and its Visual Studio .NET suite of tools were the only way to program C# (other than at the Windows command line). Since then, however, Visual Studio has gone through three major revisions — the latest is Visual Studio 2008. And at least two other players have entered the C# game.

It’s now possible to write and compile C# programs on Windows and a variety of Unix-based machines using implementations of .NET and C# such as Mono (www.mono-project.com). Mono is an open-source software project sponsored by Novell Corporation. Version 1.2 came out in November 2006. While Mono lags Microsoft’s .NET by half a version or so, it appears to be moving fast, having implemented basically all of .NET 1.1 and much of .NET 2.0, along with those versions of C#.

Both Mono and a less-well-developed competitor, Portable .NET (www.dotgnu.org/pnet.htm), claim to run C# programs on Windows and a variety of Unix flavors, including Linux and Apple’s Macintosh operating system. At this writing, Portable .NET reaches the greater number of flavors, while Mono boasts a more complete .NET implementation. So choosing between them can be complicated, depending on your project, your platform, and your goals. (Books about programming for these platforms are becoming available already. Check online booksellers.)

Open-source software is written by collaborating groups of volunteer programmers and is usually free to the world.

Making C# and other .NET languages portable to other operating systems is far beyond the scope of this book. But you can expect that within a few years, the C# Windows programs you discover how to write in this book will run on all sorts of hardware under all sorts of operating systems — matching the claim of Sun Microsystems’ Java language to run on any machine. That’s undoubtedly a good thing, even for Microsoft. The road to that point is still under construction, so it’s no doubt riddled with potholes and obstacles to true universal portability for C#. But it’s no longer just Microsoft’s road.

For the moment, however, Microsoft’s Visual Studio has the most mature versions of C# and .NET and the most feature-filled toolset for programming with them.

Note: Two authors wrote this book, but it seemed more economical to say “I” instead of “we,” so that’s what we (I?) do throughout.

What’s New in C# 3.0

While most of C# 3.0 is still virtually the same as the previous version, C# 3.0 does add some exciting new features. The big new additions that this book covers include the following:

bullet Language Integrated Query (LINQ): LINQ lets you perform operations on data using a C# syntax much like the Standard Query Language (SQL) that generations of programmers have used to work with databases. Not only does LINQ simplify database code, you can use it to write queries on Extended Markup Language (XML) files too. Chapter 17 is a gentle introduction to LINQ, covering my favorite part: using the new query syntax to work with any collection of data, including C# arrays and collections.

bullet Extension Methods, Anonymous Types, and More: Tons of cool language features that enrich C# while serving as a base to make LINQ work. I cover these features throughout the book.

bullet HashSet. A versatile new HashSet collection class, covered in Chapter 5.

Leaving aside a few of the more esoteric and advanced additions, I’ll mention a few smaller items here and there as appropriate. (Don’t worry if parts of this Introduction are Geek to you. You’ll get there.)

In addition to the brand new paint-still-wet features of C# 3.0, the book adds coverage of some older features that I just hadn’t managed to cover yet — in particular, delegates, events, and enumerations. And you’ll find beefed-up coverage of C# collection classes and much more on strings, interfaces, and exceptions, plus a host of tweaks, notes, and tips.

About This Book

The goal of this book is to explain C# to you, but to write actual programs, you need a specific coding environment. I’m betting that most readers will be using Microsoft Visual Studio, although I do suggest alternatives. In basing the book on Visual Studio, I’ve tried to keep the Visual Studio portions to a reasonable minimum. You’ll find a good tour of Visual Studio and its debugger in Bonus Chapter 6 on the Web site that accompanies this book.

I realize that many, if not most, readers will want to use C# to write graphical Windows and Web applications. C# is a powerful tool for that purpose, but that’s only one area for using C#, and this book must focus on C# as a language. To get a start in graphical Windows programs, visit my Web site at csharp102.info. I recommend you get a good grasp of C# before seeking to understand Windows programming in full. I also realize that some power users will be using C# to build Web-ready, distributed applications and database applications; however, publishing limitations require me to draw the line somewhere. C# 2008 For Dummies does not tackle the challenges of distributed programming, database programming, or some of the other new technologies such as Windows Presentation Foundation, Windows Communication Foundation, or Windows Workflow Foundation. The book does explain quite a bit of .NET, though, for the simple reason that much of C#’s power comes from the .NET Framework class libraries that it uses.

What You Need to Use the Book

At a minimum, you need the .NET Common Language Runtime (CLR) before you can even execute the programs generated by C#. Visual Studio 2008 copies the CLR onto your machine as part of the installation procedure. Alternatively, you can download the entire .NET package, including the C# compiler and many other nice tools, from Microsoft’s Web site at msdn.microsoft.com. Look for the .NET Software Development Kit (SDK). My Web site explains how to get these items.

If all you need is C#, you can download a free version of Visual Studio called Visual C# 2008 Express from msdn.microsoft.com/vstudio/express. The Express versions include C# 3.0’s new features. Alternatively, see SharpDevelop (www.icsharpcode.net), a pretty good free Visual Studio workalike, which I’ve provided on the Web site for this book. (At this writing, SharpDevelop has yet to release a version compatible with the new C# 3.0/.NET 3.5 features, but work is well under way.)

You can still create most of the programs in this book with earlier versions of Visual Studio — such as Visual Studio 2005 — if you need to. The exceptions are the programs that cover the new features available only with C# 3.0, listed above in the section “What’s New in C# 3.0”

How to Use This Book

We’ve made this book as easy to use as possible. Figuring out a new language is hard enough. Why make it any more complicated than it needs to be? The book is divided into six parts. Part I introduces you to C# programming with Visual Studio. This part guides you step by step in the creation of simple C# programs. We strongly encourage you to start here and read Chapter 1 before branching out into the other parts of the book. Even if you’ve programmed before, the basic program framework created in Part I is reused throughout the book.

The chapters in Parts II through V stand alone but have plenty of cross-references to other chapters. I’ve written these chapters so that you can open the book to any one of them and start reading. If you’re new to programming, or new to C-family languages, however, you will have to read Part II before you can jump ahead. But, except where noted, when you return to refresh your memory on some particular topic, you should have no trouble flipping to a section without the need to restart 20 pages back.

Of course, the Part of Tens finishes out the lineup, and there’s more on the Web site that accompanies the book — plus a little extra on my Web site at csharp102.info.

How This Book Is Organized

Here’s a brief rundown on what you’ll find in each part of the book.

Part I: Getting Started with C#

This part shows you, step by step, how to write basic nongraphical C# programs by developing a simple framework that’s used in the other parts of this book. You can find information about graphical programming on my site.

Part II: Basic C# Programming

At the most basic level, Shakespeare’s plays are just a series of words all strung together. By the same token, 90 percent of any C# program you ever write consists of creating variables, performing arithmetic operations, and controlling the execution path through a program. This part concentrates on these core operations and includes a new chapter explaining C#’s collection classes in detail, including the new HashSet class.

Part III: Using Objects

It’s one thing to declare variables here or there and to add and subtract them. It’s quite another thing to write real programs for real people. Part III focuses on how to organize your data to make it easier to use in creating a program.

Part IV: Object-Oriented Programming

You can organize the parts of an airplane all you want, but until you make it do something, it’s nothing more than a collection of parts. It’s not until you fire up the engines and start the wings flapping that it’s going anywhere.

In like fashion, Part IV explains the fundamentals of object-oriented programming (OOP). If you’re completely new to OOP, Part IV should provide a smooth transition. And a much-improved chapter on interfaces takes you beyond the usual OOP fundamentals.

Part V: Now Showing in C# 3.0

After the airplane gets off the ground, it has to go somewhere. In this book, you’ll be flying fearlessly into the new C# 3.0 features. In particular, you can upgrade your C# skills to command-pilot level with the new Language Integrated Query (LINQ) now built right into C#. The objects and collections of objects that you’ve been exploring in previous parts of the book set new cross-country flight records when you start writing LINQ queries. To help you get up to speed, I’ve added a new chapter on delegates and events.

Part VI: The Part of Tens

C# is great at finding errors in your programs — at times, it seems a little too good at pointing out my shortcomings. However, believe it or not, C# is trying to do you a favor. Every problem it finds is another problem that you would otherwise have to find on your own.

Unfortunately, the error messages can be confusing. This part presents the ten most common C# build error messages, what they mean, and how the heck to get rid of them.

Many readers are coming to C# from another programming language. You can find a few helpful comments on the transition you’re making on my Web site.

About the Web site

The Web site contains a host of goodies. First, you find an expanded collection of all the source code from this book. A set of utilities is also included. I’ve used the SharpDevelop utility enough to know that it’s up to the task of writing almost any of the example programs in this book (with the possible exception, for now, of the new LINQ features). The Reflector tool lets you peek under the covers to see what the compiler has turned your lovely C# source code into. The NUnit testing tool, wildly popular among C# programmers, makes testing your code easy, whether from Visual Studio or SharpDevelop. Finally, the Web site contains a bunch of bonus chapters covering features and techniques that wouldn’t fit into the book, including a tour of Visual Studio.

Don’t forget the ReadMe file, which has all the most up-to-date information.

Icons Used in This Book

Throughout the pages of this book, I use the following icons to highlight important information.

This icon flags technical stuff that you can skip on the first reading.

The Tip icon highlights a point that can save you a lot of time and effort.

Remember this. It’s important.

Remember this, too. This one can sneak up on you when you least expect it and generate one of those really hard-to-find bugs — or it may lead you down the garden path into La-La Land.

This icon identifies code that you can find on the Web site with this book. This feature is designed to save you some typing when your fingers start to cramp, but don’t abuse it. You’ll gain a better understanding of C# by entering the programs yourself, then using them as test beds for your explorations and experiments in C#.

Conventions Used in This Book

Throughout this book, I use several conventions to help you out. Terms that are not “real words,” such as the name of some program variable, appear in this font to minimize the confusion factor. Program listings are offset from text as follows:

use System;

namespace MyNameSpace


  public class MyClass




Each listing is followed by a clever, insightful explanation. Complete programs are included on the Web site for your viewing pleasure. Small code segments are not.

Finally, you’ll see command arrows, as in the phrase, “Choose File⇒Open WithNotepad.” That means choose the File menu option. Then, from the pull-down menu that appears, choose Open With. Finally, from the resulting submenu, choose Notepad.

Where’s the Code? And the Bonus Goodies?

In a departure from previous editions of this book, this time we chose to provide all of the code examples, along with several bonus chapters, on the Web. Thus you won’t find a CD-ROM tucked into the back cover. You can obtain the code and bonus chapters on two different Web sites:

bullet www.dummies.com

Here, along with the code and bonus chapters, you can track down For Dummies titles mentioned in the book — and many related titles as well.

bullet csharp102.info, my Web site.

Here you’ll find all of that same bonus material. But you’ll also find lots of articles that extend topics in the book or introduce new topics that I’d have liked to put in the book — only of course it’s impossible to include everything. The site also points you to a number of programming tools and other C# resources.

Don’t forget the ReadMe file — also available on both Web sites — which has all the most up-to-date information.

Where to Go from Here

Obviously, the first step is to figure out the C# language, ideally using C# 2008 For Dummies, of course. You may want to give yourself a few months of writing simple C# programs before taking on the next step of discovering how to create graphical Windows applications. Give yourself many months of Windows application experience before you branch out into writing programs intended to be distributed over the Internet.

In the meantime, you can keep up with C# goings and comings in several locations. First, check out the official source: msdn.microsoft.com/msdn. In addition, various programmer Web sites have extensive material on C#, including lively discussions all the way from how to save a source file to the relative merits of deterministic versus nondeterministic garbage collection. Around my house, garbage collection is very deterministic: It’s every Wednesday morning. Here are a few large C# sites:

bullet msdn.microsoft.com/vcsharp, the C# home page, which gets you to all sorts of C# and .NET resources

bullet blogs.msdn.com/csharpfaq, a C# Frequently Asked Questions blog

bullet msdn.microsoft.com/vcsharp/team/blogs, which is comprised of personal blogs of C# team members

bullet www.c-sharpcorner.com and www.codeproject.com, two major C# sites with articles, blogs, code, job information, and other C# resources

I maintain a Web site, csharp102.info, containing a set of Frequently Asked Questions (FAQs). If you encounter something that you can’t figure out, try going there — maybe the FAQs have already answered your question. In addition, the site includes a list of any mistakes that may have crept into the book, the book’s example code, several bonus chapters, and tons of other material on C# and programming that you may find useful. Finally, you can find a link to my e-mail address, in case you can’t find the answer to your question on the site.

Part I

Getting Started with C#

In this part . . .

You have a long way to go before you’ve mastered C#, so have a little fun just to get off the ground. Part I takes you through the steps for creating the most basic Windows console application possible, using Visual Studio 2008. The result gives you the basic C# framework for the example programs that appear throughout this book.