27,99 €
A logical, straightforward approach to learning the C# language C# is a complicated programming language for building .NET-connected software for Microsoft Windows, the Web, and a wide range of devices. The friendly All-in-One For Dummies format is a perfect way to present it. Each minibook is a self-contained package of necessary information, making it easy to find what you're looking for. Upgrades in C# 2010 include the ability to build Windows 7 applications and compatibility with Python and Ruby. * C# is a somewhat complex programming language for building .NET-connected software for Microsoft Windows, the Web, and other devices * Beginning C# programmers will appreciate how the All-in-One format breaks the topic into minibooks, each one addressing a key body of information * Minibooks include creating your first C# program, Windows 7 programming, basic C# programming, object-based programming, object-oriented programming, Windows programming with C# and Visual Studio, and debugging * Companion Web site includes all sample code Beginning C# programmers will find C# 2010 All-in-One For Dummies explains a complicated topic in an easy, understandable way. Note: CD-ROM/DVD and other supplementary materials are not included as part of eBook file.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 1121
Veröffentlichungsjahr: 2010
Table of Contents
Introduction
What’s New in C# 4.0
About This Book
What You Need in Order to Use This Book
How to Use This Book
How This Book Is Organized
Book I: The Basics of C# Programming
Book II: Object-Oriented C# Programming
Book III: Designing for C#
Book IV: A Tour of Visual Studio
Book V: Windows Development with WPF
Book VI: Web Development with ASP.NET
Book VII: Service-Oriented Development
Book VIII: New Features in C# 4.0
Icons Used in This Book
Conventions Used in This Book
About this book’s Web site
Where to Go from Here
Book I: Basics of C# Programming
Book I: Chapter 1: Creating Your First C# Console Application
Getting a Handle on Computer Languages, C#, and .NET
What’s a program?
What’s C#?
What’s .NET?
What is Visual Studio 2010? What about Visual C#?
Creating Your First Console Application
Creating the source program
Taking it out for a test drive
Making Your Console App Do Something
Reviewing Your Console Application
The program framework
Comments
The meat of the program
Introducing the Toolbox Trick
Saving code in the Toolbox
Reusing code from the Toolbox
Book I: Chapter 2: Living with Variability — Declaring Value-Type Variables
Declaring a Variable
What’s an int?
Rules for declaring variables
Variations on a theme: Different types of int
Representing Fractions
Handling Floating-Point Variables
Declaring a floating-point variable
Converting some more temperatures
Examining some limitations of floating-point variables
Using the Decimal Type: Is It an Integer or a Float?
Declaring a decimal
Comparing decimals, integers, and floating-point types
Examining the bool Type: Is It Logical?
Checking Out Character Types
The char variable type
Special chars
The string type
What’s a Value Type?
Comparing string and char
Calculating Leap Years: DateTime
Declaring Numeric Constants
Changing Types: The Cast
Letting the C# Compiler Infer Data Types
Book I: Chapter 3: Pulling Strings
The Union Is Indivisible, and So Are Strings
Performing Common Operations on a String
Comparing Strings
Equality for all strings: The Compare() method
Would you like your compares with or without case?
What If I Want to Switch Case?
Distinguishing between all-uppercase and all-lowercase strings
Converting a string to upper- or lowercase
Looping through a String
Searching Strings
Can I find it?
Is my string empty?
Getting Input from the Command Line
Trimming excess white space
Parsing numeric input
Handling a series of numbers
Joining an array of strings into one string
Controlling Output Manually
Using the Trim() and Pad() methods
Using the Concatenate() method
Let’s Split() that concatenate program
Formatting Your Strings Precisely
StringBuilder: Manipulating Strings More Efficiently
Book I: Chapter 4: Smooth Operators
Performing Arithmetic
Simple operators
Operating orders
The assignment operator
The increment operator
Performing Logical Comparisons — Is That Logical?
Comparing floating-point numbers: Is your float bigger than mine?
Compounding the confusion with compound logical operations
Matching Expression Types at TrackDownAMate.com
Calculating the type of an operation
Assigning types
Book I: Chapter 5: Getting Into the Program Flow
Branching Out with if and switch
Introducing the if statement
Examining the else statement
Avoiding even the else
Nesting if statements
Running the switchboard
Here We Go Loop-the-Loop
Looping for a while
Doing the do . . . while loop
Breaking up is easy to do
Looping until you get it right
Focusing on scope rules
Looping a Specified Number of Times with for
An example
Why do you need another loop?
Nesting Loops
Don’t goto Pieces
Book I: Chapter 6: Lining Up Your Ducks with Collections
The C# Array
The argument for the array
The fixed-value array
The variable-length array
The Length property
Initializing an array
A Loop Made foreach Array
Sorting Arrays of Data
New Feature: Using var for Arrays
Loosening Up with C# Collections
Understanding Collection Syntax
Figuring out <T>
Going generic
Using Lists
Using Dictionaries
Array and Collection Initializers
Initializing arrays
Initializing collections
Using Sets
On Not Using Old-Fashioned Collections
Book I: Chapter 7: Stepping through Collections
Iterating through a Directory of Files
Iterating foreach Collections: Iterators
Accessing a collection: The general problem
Letting C# access data foreach container
Accessing Collections the Array Way: Indexers
Indexer format
An indexer program example
Looping Around the Iterator Block
Iterating days of the month: A first example
What a collection is, really
Iterator syntax gives up so easily
Iterator blocks of all shapes and sizes
Where you can put your iterator
Book I: Chapter 8: Buying Generic
Writing a New Prescription: Generics
Generics are type-safe
Generics are efficient
Classy Generics: Writing Your Own
Shipping packages at OOPs
Queuing at OOPs: PriorityQueue
Unwrapping the package
Touring Main()
Writing generic code the easy way
Saving PriorityQueue for last
Using a (nongeneric) Simple Factory class
Tending to unfinished business
Book I: Chapter 9: Some Exceptional Exceptions
Using an Exceptional Error-Reporting Mechanism
About try blocks
About catch blocks
About finally blocks
What happens when an exception is thrown
Throwing Exceptions Yourself
Knowing What Exceptions Are For
Can I Get an Exceptional Example?
Knowing what makes the example exceptional
Tracing the stack
Assigning Multiple catch Blocks
Planning Your Exception-Handling Strategy
Some questions to guide your planning
Guidelines for code that handles errors well
How to analyze a method for possible exceptions
How to find out which methods throw which exceptions
Grabbing Your Last Chance to Catch an Exception
Book II: Object-Oriented C# Programming
Book II: Chapter 1: Object-Oriented Programming: What’s It All About?
Object-Oriented Concept #1: Abstraction
Preparing procedural nachos
Preparing object-oriented nachos
Object-Oriented Concept #2: Classification
Why Classify?
Object-Oriented Concept #3: Usable Interfaces
Object-Oriented Concept #4: Access Control
How C# Supports Object-Oriented Concepts
Book II: Chapter 2: Showing Some Class
Defining a Class and an Object
Defining a class
What’s the object?
Accessing the Members of an Object
An Object-Based Program Example
Discriminating between Objects
Can You Give Me References?
Classes That Contain Classes Are the Happiest Classes in the World
Generating Static in Class Members
Defining const and readonly Data Members
Book II: Chapter 3: We Have Our Methods
Defining and Using a Method
A Method Example for Your Files
Having Arguments with Methods
Passing an argument to a method
Passing multiple arguments to methods
Matching argument definitions with usage
Overloading a method doesn’t mean giving it too much to do
Implementing default arguments
Returning Values after Christmas
Returning a value via return postage
Defining a method with no value
Book II: Chapter 4: Let Me Say This about this
Passing an Object to a Method
Defining Methods
Defining a static method
Defining an instance method
Expanding a method’s full name
Accessing the Current Object
What is the this keyword?
When is this explicit?
What happens when you don’t have this?
Book II: Chapter 5: Holding a Class Responsible
Restricting Access to Class Members
A public example of public BankAccount
Jumping ahead — other levels of security
Why You Should Worry about Access Control
Accessor methods
Access control to the rescue — an example
So what?
Defining Class Properties
Static properties
Properties with side effects
New feature: Letting the compiler write properties for you
Accessors with access levels
Getting Your Objects Off to a Good Start — Constructors
The C#-Provided Constructor
Replacing the Default Constructor
Constructing something
Executing the constructor from the debugger
Initializing an object directly with an initializer
Seeing that construction stuff with initializers
New feature: Initializing an object without a constructor
Book II: Chapter 6: Inheritance: Is That All I Get?
Class Inheritance
Why You Need Inheritance
Inheriting from a BankAccount Class (A More Complex Example)
IS_A versus HAS_A — I’m So Confused_A
The IS_A relationship
Gaining access to BankAccount by using containment
The HAS_A relationship
When to IS_A and When to HAS_A
Other Features That Support Inheritance
Substitutable classes
Invalid casts at run time
Avoiding invalid conversions with the is operator
Avoiding invalid conversions with the as operator
The object Class
Inheritance and the Constructor
Invoking the default base class constructor
Passing arguments to the base class constructor — mama sang base
Getting specific with base
The Updated BankAccount Class
Book II: Chapter 7: Poly-what-ism?
Overloading an Inherited Method
It’s a simple case of method overloading
Different class, different method
Peek-a-boo — hiding a base class method
Calling back to base
Polymorphism
Using the declared type every time (Is that so wrong?)
Using is to access a hidden method polymorphically
Declaring a method virtual and overriding it
Getting the most benefit from polymorphism — the do-to-each trick
The Class Business Card: ToString()
C# During Its Abstract Period
Class factoring
The abstract class: Left with nothing but a concept
How do you use an abstract class?
Creating an abstract object — not!
Sealing a Class
Book II: Chapter 8: Interfacing with the Interface
Introducing CAN_BE_USED_AS
Knowing What an Interface Is
How to implement an interface
How to name your interface
Why C# includes interfaces
Mixing inheritance and interface implementation
And he-e-e-re’s the payoff
Using an Interface
As a method return type
As the base type of an array or collection
As a more general type of object reference
Using the C# Predefined Interface Types
Looking at a Program That CAN_BE_USED_AS an Example
Creating your own interface at home in your spare time
Implementing the incomparable IComparable<T> interface
Putting it all together
Getting back to the Main() event
Unifying Class Hierarchies
Hiding Behind an Interface
Inheriting an Interface
Using Interfaces to Manage Change in Object-Oriented Programs
Making flexible dependencies through interfaces
Abstract or concrete: When to use an abstract class and when to use an interface
Doing HAS_A with interfaces
Book II: Chapter 9: Delegating Those Important Events
E.T., Phone Home — The Callback Problem
Defining a Delegate
Pass Me the Code, Please — Examples
I delegated the example to Igor
First, a simple example
A More Real-World Example
Getting an overview of the bigger example
Putting the app together
Looking at the code
Tracking the delegate life cycle
Shh! Keep It Quiet — Anonymous Methods
Stuff Happens — C# Events
The Observer design pattern
What’s an event? Publish/Subscribe
How a publisher advertises its events
How subscribers subscribe to an event
How to publish an event
How to pass extra information to an event handler
A recommended way to raise your events
How observers “handle” an event
Book II: Chapter 10: Can I Use Your Namespace in the Library?
Dividing a Single Program into Multiple Source Files
Dividing a Single Program into Multiple Assemblies
Executable or library?
Assemblies
Executables
Class libraries
Putting Your Classes into Class Libraries
Creating the projects for a class library
Creating a stand-alone class library
Adding a second project to an existing solution
Creating classes for the library
Using a driver program to test a library
Using a class library from a program
Going Beyond Public and Private: More Access Keywords
Internal: Eyes only at the CIA
Protected: Sharing with subclasses
Protected internal: Being a more generous protector
Putting Classes into Namespaces
Declaring a namespace
Relating namespaces to the access keyword story
Using fully qualified names
Book III: Designing for C#
Book III: Chapter 1: Writing Secure Code
Designing Secure Software
Determining what to protect
Documenting the components of the program
Decomposing components into functions
Identifying potential threats in functions
Rating the risk
Building Secure Windows Applications
Authentication using Windows login
Encrypting information
Deployment security
Building Secure Web Forms Applications
SQL Injection attacks
Script exploits
Best practices for securing Web Forms applications
Using System.Security
Book III: Chapter 2: Accessing Data
Getting to Know System.Data
How the Data Classes Fit into the Framework
Getting to Your Data
Using the System.Data Namespace
Setting up a sample database schema
Connecting to a data source
Working with the visual tools
Writing data code
Using the Entity Framework
Book III: Chapter 3: Fishing the FileStream
Going Where the Fish Are: The File Stream
Streams
Readers and writers
StreamWriting for Old Walter
Using the stream: An example
Revving up a new outboard StreamWriter
Finally, we’re writing!
Using some better fishing gear: The using statement
Pulling Them Out of the Stream: Using StreamReader
More Readers and Writers
Exploring More Streams than Lewis and Clark
Book III: Chapter 4: Accessing the Internet
Getting to Know System.Net
How Net Classes Fit into the Framework
Using the System.Net Namespace
Checking the network status
Downloading a file from the Internet
E-mailing a status report
Logging network activity
Book III: Chapter 5: Creating Images
Getting to Know System.Drawing
Graphics
Pens
Brushes
Text
How the Drawing Classes Fit into the Framework
Using the System.Drawing Namespace
Getting started
Setting up the project
Drawing the board
Book IV: A Tour of Visual Studio
Book IV: Chapter 1: Getting Started with Visual Studio
Versioning the Versions
Express
Professional
Team System
MSDN
Academic
An edition breakdown
Installing Visual Studio
Breaking Down the Projects
Exploring the New Project dialog box
Understanding solutions and projects
A brief survey of the available project categories
Book IV: Chapter 2: Using the Interface
Designing in the Designer
Windows Presentation Foundation (WPF)
Windows Forms
Web Forms
Class Designer
Paneling the Studio
Solution Explorer
Properties
The Toolbox
Server Explorer
Class View
Coding in Code View
Exercising the Code Viewer
Exploring the auxiliary windows
Using the Tools of the Trade
The Tools menu
Building and Debugging
Refactor menu
Book IV: Chapter 3: Customizing Visual Studio
Setting Options
Environment
Language
Neat stuff
Using Snippets
Using snippets
Using surround snippets
Making snippets
Deploying snippets
Sharing snippets
Hacking the Project Types
Hacking Project templates
Hacking item templates
Book IV: Chapter 4: Transforming Text Templates
Getting to Know T4
Looking back at the DSL Tools
Looking ahead to what it became
Figuring Out When to Use T4
Replacing repetitive coding
Building code based on outside data
Setting Up the Environment
Changing the security settings
Creating a template from a text file
Using Some of the T4 Directives
Setting the output
Configuring a template
Including includes
Importing items and assemblies
Book V: Windows Development with WPF
Book V: Chapter 1: Introducing WPF
Understanding What WPF Can Do
Introducing XAML
Diving In! Creating Your First WPF Application
Declaring an application-scoped resource
Making the application do something
Whatever XAML Can Do, C# Can Do Better!
Book V: Chapter 2: Understanding the Basics of WPF
Using WPF to Lay Out Your Application
Arranging Elements with Layout Panels
The Stack Panel
The Wrap Panel
The Dock Panel
Canvas
The Uniform Grid
The Grid
Putting it all together with a simple data entry form
Panels of honorable mention
Exploring Common XAML Controls
Display only controls
Basic input controls
List-based controls
Book V: Chapter 3: Data Binding in WPF
Getting to Know Dependency Properties
Exploring the Binding Modes
Investigating the Binding Object
Defining a binding with XAML
Defining a binding with C#
Editing, Validating, Converting, and Visualizing Your Data
Validating data
Converting your data
Finding Out More about WPF Data Binding
Book V: Chapter 4: Practical WPF
Commanding Attention
ICommand
Routed commands
Built-in commands
Focus!
Custom commands
Separation of Concerns and testability
Get Your ViewModel On
Who cares?
Tradition!
Show me the code!
Book VI: Web Development with ASP.NET
Book VI: Chapter 1: Looking at How ASP.NET Works with C#
Breaking Down Web Applications
Questioning the Client
Scripting the client
Getting information back from the client
Understanding the weaknesses of the browser
Dealing with Web Servers
Getting a PostBack (Hint: It’s not a returned package)
It’s a matter of state
Book VI: Chapter 2: Building Web Applications
Working in Visual Studio
Handling the Designer
Coding in Code View
Recognizing the other file types
Developing with Style
Coding behind
Scripting the experience
Building in n-tier
Modeling the View Controller
Book VI: Chapter 3: Controlling Your Development Experience
Showing Stuff to the User
Labels versus plain old text
Images
Panels and multiviews
Tables
Getting Some Input from the User
Using text input controls
Using single-item selection controls
Using multiple-item selection controls
Using other kinds of input controls
Submitting input with Submit buttons
Data Binding
Setting up your markup for binding
Data binding using the code-behind
Using commonly bound controls
Styling Your Controls
Setting control properties
Binding styles with CSS
Making Sure the Site Is Accessible
Control features for accessibility
Design considerations
Constructing User Controls
Making a new phone number user control
Using your new control
Adding Custom Controls
Book VI: Chapter 4: Leveraging the .NET Framework
Surfing Web Streams
Intercepting the request
Altering content sent to clients
Securing with ASP.NET
Changing trusts
Fixing problems
Navigating with Site Maps
Adding a site map
Navigating a site with SiteMap
Managing Files
Baking Cookies
Coding for client-side storage
Wrangling cookies on the server
How ASP.NET manages cookies for you
Tracing with TraceContext
Book VI: Chapter 5: Digging into Web Construction
Managing Files
Reviewing project types
Reviewing file types
Organizing files
Mastering Master Pages
Making a master page
Adding content
Testing Web Applications with Visual Studio
Deploying Your Masterpiece
Lots of options
Copying Web sites with “Copy Web”
Package/Publish
Book VII: Service-Oriented Development
Book VII: Chapter 1: Getting Acquainted with Web Services
Understanding Web Services
Loosely coupled
Contract driven
Chunky versus chatty
Building Service-Oriented Applications
Providing XML Web Services
Building Three Sample Apps
Book VII: Chapter 2: Building Web Services with ASMX
Getting to Know SOAP
SOAP and standards
The WS-* standards
The impact to you
Big, fat, and slow
Making an ASMX Service
Creating a new service
Building the code for SHARP
Deploying
Consuming services in your applications
Book VII: Chapter 3: Building Web Services with WCF
Getting to Know WCF
Creating a WCF Service
Breaking it down
Making a registration service
Configuring
Deploying
Consuming
Book VII: Chapter 4: Building Web Services with ReST
Getting to Know ReST
Understanding the Guiding Principles of ReST
Diving into the details of ReST
Changing a WCF Service to Use ReST
Getting the WCF service
Exposing the ReST service
Returning data in different ways
Book VIII: New Features in C# 4.0
Book VIII: Chapter 1: Programming Dynamically!
Shifting C# Toward Dynamic Typing
Programming Dynamically
Putting Dynamic to Use
Classic examples
Making static operations dynamic
Understanding what’s happening under the covers
Running with the Dynamic Language Runtime
Dynamic Ruby
Dynamic C#
Book VIII: Chapter 2: Improving Productivity with Named and Optional Parameters
Optional Parameters
Reference types
Output parameters
Named Parameters
Overload Resolution
Book VIII: Chapter 3: Helping Out with Interop
Using Dynamic Import
Working without Primary Interop Assemblies
Skipping the Ref Statement
Book VIII: Chapter 4: Revising Generics
Variance
Contravariance
Covariance
C# 2010 All-in-One For Dummies®
by Bill Sempf, Charles Sphar, and Stephen Randy Davis
C# 2010 All-in-One For Dummies®
Published byWiley Publishing, Inc.111 River St.Hoboken, NJ 07030-5774www.wiley.com
Copyright © 2010 by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
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.
Trademarks: Wiley, the Wiley Publishing logo, For Dummies, the Dummies Man logo, A Reference for the Rest of Us!, The Dummies Way, Dummies Daily, The Fun and Easy Way, Dummies.com, Making Everything Easier, 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. 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.
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 Website 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 Website may provide or recommendations it may make. Further, readers should be aware that Internet Websites 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 U.S. at 877-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002.
For technical support, please visit www.wiley.com/techsupport.
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: 2010925120
ISBN: 978-0-470-56348-9
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
About the Authors
Hi, my name is Bill Sempf, and I am a software architect. Although I used to hate the term architect, it’s clearly the only thing out there that defines what I do. My breadth of experience includes business and technical analysis, software design, development, testing, server management and maintenance, and security. In my 17 years of professional experience, I have participated in the creation of well over 200 applications for large and small companies, managed the software infrastructure of two Internet service providers, coded complex software happily in every environment imaginable, and made mainframes talk to cellphones. In short, I make the technology products that people are using every day play nicely together.
I started playing with computers in 1979 and haven’t looked back since. In 1985 I was helping my father (also named Bill) manage Apple IIe systems at the local library. Since then I have built applications for the likes of Bank One, Lucent Technologies, Nationwide Insurance, and Sears, Roebuck and Co. I am the author of Visual Basic 2008 For Dummies and Visual Basic 2005 For Dummies; a coauthor of Effective Visual Studio.NET, Professional ASP.NET Web Services, and Professional VB.NET; a frequent contributor to MSDN, Builder.com, Hardcore Web Services, Cloud Computing Journal, Inside Web Development Journal, and Intranet Journal; and have recently been an invited speaker for the ACM and IEEE, DevEssentials, the International XML Web Services Expo, and the Association of Information Technology Professionals. I am a graduate of The Ohio State University with a bachelor’s of science degree in business administration, a Microsoft Certified Professional, a Certified Internet Business Strategist, and a Certified Internet Webmaster. My company is Products Of Innovative New Technology (usually called POINT), and you can reach me at place text here bill@pointWeb.net.
Chuck Sphar escaped the Microsoft C++ documentation camps after six years of hard labor as a senior technical writer. You can reach Chuck for praise and minor nits at csharp@chucksphar.com. His C# material Web page (references throughout the book) is csharp102.info.
Stephen R. Davis, who goes by the name Randy, lives with his wife and son near Dallas, Texas.
Dedication
This book goes to the active community of Microsoft developers that I get to work with every day. Thanks for your commitment to getting things done right, sharing what you know, and having a good time doing it.
Also, for Gabrielle and Adam, who had to put up with another six months of Daddy hiding in the basement.
—Sempf
Authors' Acknowledgments
A lot of people work to make a book of this size. Don’t think, just because the authors are listed on the front page, that they conceived every idea in the book. It takes a community.
First, thanks to Chuck Sphar and Randy Davis for the fantastic source material that is the backbone of this book. I learned much just editing the first two minibooks for use in this All-in-One. Also, thanks to Katie Feltman and Chris Morris for their editorial expertise.
A number of community members had a huge part in the creation of this book. Carey Payette and Phil Japikse built Book V (about WPF) basically from the goodness of their hearts, and I couldn’t have completed it without them — my WPF skills aren’t worth writing about. These two get the award for Biggest Contribution, and I thank them both.
The developers at Information Control Corporation were also essential in formulating the initial scope of this book and then fact-checking the details. Steve Webb, Stephen Giffin, John Hannah, Larry Beall, Michael Birchmeyer, and Azher Muhammad all had a big part, especially in the information related specifically to C# 4.0. Thanks to them and all the other ICC experts who gave me ideas and tips.
Kevin Pilch-Bisson at Microsoft provided some C# clarity via Twitter throughout the scope of this book. Steve Andrews provided the structure for the T4 chapter in Book IV. Mads Torgerson reviewed the table of contents, and I thank him for the “It looks delicious” phrase, which I think was my most quoted phrase of the year.
Lars Corneliussen provided a few choice pointers for the book, and Julie Lerman’s Entity Framework writing was the basis of my own additions to the ADO.NET chapter.
As always, thanks to my wife, Gabrielle, for her support. Sometimes I just can’t believe how lucky I am.
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
Senior Project Editor: Christopher Morris
Acquisitions Editor: Katie Feltman
Copy Editors: Debbye Butler, Heidi Unger, Becky Whitney
Technical Editor: Mike Spivey
Editorial Manager: Kevin Kirschner
Media Development Project Manager: Laura Moss-Hollister
Media Development Assistant Project Manager: Jenny Swisher
Media Development Associate Producers: Josh Frank, Marilyn Hummel, Douglas Kuhn, Shawn Patrick
Editorial Assistant: Amanda Graham
Sr. Editorial Assistant: Cherie Case
Cartoons: Rich Tennant (www.the5thwave.com)
Composition Services
Project Coordinator: Sheree Montgomery
Layout and Graphics: Samantha K. Cherolis, Nikki Gately, Joyce Haughey
Proofreader: Christine Sabooni
Indexer: Broccoli Information Mgt.
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
Composition Services
Debbie Stailey, Director of Composition Services
Introduction
C# 2010 All-in-One For Dummies represents a different way of looking at programming languages. Rather than present the standard For Dummies format, which includes only 350 pages on quite a large subject, the book was expanded to include a broader scope and just a few pages were added.
So, although you find all the original C# For Dummies goodness in this book, you also find discussions about Visual Studio, Windows Presentation Foundation (WPF), service-oriented development, Web development, and a host of other topics. This book is a one-stop shop for a C# developer.
The C# programming language is a powerful and, at some nine years old, relatively mature descendant of the earlier C, C++, and Java languages. Programming with C# is lots of fun, as you’re about to find out in this book.
Microsoft created C# as a major part of its .NET initiative. The company turned over the specifications for the C# language to the ECMA (pronounced “ek-ma”) international standards committee in the summer of 2000 so that any company can, in theory, 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 was published, the Microsoft C# compiler was the only game in town, and its Visual Studio .NET suite of tools was the only way to program C# (other than at the Windows command line). Since then, however, Visual Studio has undergone three major revisions — the latest is Visual Studio 2010. And, at least two other players have entered the C# game.
You can now 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), an open source software project sponsored by Novell Corporation. Version 1.2 was released in November 2006. Though Mono lags Microsoft .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 the Apple Macintosh operating system. At the time of this writing, Portable .NET reaches the greater number of flavors, whereas 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.
A description of how to make 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 Visual Studio has the most mature versions of C# and .NET and the most feature-filled toolset for programming with them.
Note: Though three authors contributed to this book, saying I rather than we throughout the main text seemed more economical, so that’s what we (or I) do throughout.
What’s New in C# 4.0
Although much of C# 4.0 is still virtually the same as the previous version, this new version adds some exciting new features, most of which revolve around COM Interop, to assist with Office development. The big new additions that this book covers include these topics:
♦ Dynamic types: Functional programming is all the rage these days, with the cool kids programming in Ruby and Haskell. Functional programming certainly has some benefits that have a place in the more tightly woven world of C#, and dynamic typing is one of them. As supported in C++ and Visual Basic, dynamic types allow runtime declaration when you don’t know the type of a variable and then have the compiler figure it out. Properly used, dynamic typing is quite powerful; poorly used, it’s quite dangerous.
♦ Named and optional parameters: In C# 3.0, you had to provide a value for every parameter in a method call. In C# 4.0 — again, to optimize interactions with COM — you can mark parameters as optional and accept outside objects that have optional parameters.
♦ Variance in generics: Although objects in previous versions of C# are variant, generic collections of objects are invariant. This statement means that although the compiler accepts an apple when you’re asked for a fruit, it doesn’t accept a basket of apples when you’re asked for a basket of fruit. This issue is fixed in C# 4.0.
Leaving aside a few of the more esoteric and advanced additions, we 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.)
Because the features of C# 4.0 all tie together for use in a single major operation — COM Interop — we bundled discussions of these features in the back of this book, in Book VIII. Throughout this book, we have updated chapters from the original C# 3.0 material wherever it seemed appropriate.
About This Book
The goal of this book is to explain C# to you. To write usable programs, you need a specific coding environment. We’re betting that most readers will use Microsoft Visual Studio, although we suggest alternatives. Because this book is an All-in-One, we give you comprehensive coverage of Visual Studio in Book IV.
The original version of C# For Dummies (like all programming language books) focused on C# as a language, not all of the things you do with C#. This version of the book — in the mondo-size All-in-One format — covers Windows development, Web development, service development, and .NET Framework development, such as graphics and databases.
Our goal is to make a one-stop shop for development with Microsoft products, though there is indeed more to the topics than fits in this book. Office development isn’t covered, for instance. SharePoint has way too much going on to cover it along with everything else (although Bill co-authored VSTO For Dummies). This book is designed to handle the vast majority of C# users, though 20 percent of our readers will be working on something that we don’t cover. Sorry about that — we’ll try to stretch the book to 1,000 pages next time.
Another point is that every programming problem is different. Although many different situations are covered between the covers of this book, your specific situation is different. Some interpolation has to be taking place. If you have a question about how your personal situation fits in, send the author an e-mail at csharpfordummies.net and we’ll try to help.
What You Need in Order to Use This Book
You need, at minimum, the .NET Common Language Runtime (CLR) before you can even execute the programs generated by C#. Visual Studio 2010 copies the CLR onto your machine as part of its installation procedure. Alternatively, you can download the entire .NET package, including the C# compiler and many other useful tools, from the Microsoft Web site at msdn.microsoft.com. Look for the .NET Software Development Kit (SDK). The book’s Web site at csharpfordummies.net explains how to get these items.
If all you need is C#, you can download the free version of Visual Studio, Visual C# 2010 Express, from msdn.microsoft.com/vstudio/express. The Express versions include the new C# 4.0 features. Alternatively, see SharpDevelop (www.icsharpcode.net), a good, free Visual Studio “workalike,” which are provided on the Web site for this book.
You can still create most of the programs in this book using earlier versions of Visual Studio, such as Visual Studio 2008, if you need to. The exceptions are the programs that cover the new features available only in C# 4.0, which we describe in Book VIII.
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? Though this book is divided into eight minibooks, we use an even easier subdivision.
Books I and II comprise the bulk of the original C# For Dummies book, and they cover the C# language, updated for version 4.0. Books III and IV cover technologies that are peripheral to C#. Books V, VI, and VII cover the three main types of development you do in C# — Windows Presentation Foundation, Web development, and service-oriented programming. We finish with the (thankfully short) Book VIII, about new C# 4.0 features.
If you’re brand new, start at the beginning and read the first two minibooks. You’ll discover a lot. Really. It will seem as though you’re reading a lot of text, but it is engaging and has interesting examples.
If you’re using the .NET Framework (which you probably are), read Book III as well. If you’re using Visual Studio, read Book IV. (Note that we use Visual Studio 2010 Professional edition, so if you’re using Express or Ultimate, your screens might look slightly different.)
Finally, you can focus on your project type — Books V, VI, and VII are specific to project type, and you can pick and choose what to read. These three minibooks are organized more as a collection of related articles than as discrete book units. You’ll find them easier to use that way.
How This Book Is Organized
Here’s a brief rundown of what you’ll find in each part of this book.
Book I: The Basics of C# Programming
This minibook is the first of two that are based on the original C# For Dummies.
Book II: Object-Oriented C# Programming
In Book II, we dig into the meat of the matter and discuss which tasks C# is good for. This minibook covers how to create good class libraries and use the built-in libraries correctly. We also give you a good dose of theory and practical knowledge.
Book III: Designing for C#
.NET is essentially the set of libraries that you get to use with C#. This broad topic covers almost everything that Microsoft products can do, from coding for Windows Mobile to accessing XML files. Book III covers four of the most-needed topics:
♦ Databases
♦ Files
♦ Graphics
♦ Security
Book IV: A Tour of Visual Studio
Because Visual Studio is the tool that 95 percent of C# programmers use, it’s the tool that is the focus of Book IV. It covers the use, optimization, and customization of this graphical user interface.
Book V: Windows Development with WPF
This minibook is an unconventional choice for Windows development. For years in .NET — since its inception — the choice for Windows developers was Windows Forms, the successor to the Ruby engine in Visual Basic 6. That’s just how you build Windows applications.
Even with the introduction of C# 4.0 and Visual Studio 2010, Windows Forms is likely the most common choice for development of Windows applications. However, it’s not the future. Windows Presentation Foundation — built on the XML derivative XAML — is the future.
For that reason, we include chapters on Windows development with WPF. If you’re looking for Windows Forms 101, we include it at csharpfordummies.net.
Book VI: Web Development with ASP.NET
Some people would argue that ASP.NET Web Forms is falling by the wayside because of ASP.NET MVC, but we believe that it’s a version or two away. In this book, we look at ASP.NET application creation and form controls and the other usual suspects. (Look for MVC in the next edition of this book, though.)
Book VII: Service-Oriented Development
On the topic of Web services, we decided to give you an overview. Our experience shows that ASP.NET Web Services, Windows Communication Foundation (WCF), and REpresentational State Transfer, or ReST, are all used in the wild, so we describe a piece of all of them.
Book VIII: New Features in C# 4.0
In the last minibook in this book, we describe some of the new features in C# 4.0, with a focus on the COM Interop changes.
Icons Used in This Book
Throughout the pages of this book, we use the following icons to highlight important information:
This scary-sounding icon flags technical information that you can skip on your first pass through the book.
The Tip icon highlights a point that can save you a lot of time and effort.
Remember this information. It’s important.
Try to retain any Warning information you come across, too. This one can sneak up on you when you least expect it and generate one of those extremely hard-to-find bugs. Or, it may lead you down the garden path to La-La Land.
This icon identifies code samples you can find on the book’s Web sites. Csharp102.info has the samples for Book I and II, and many of the articles. Csharpfordummies.net has a current blog, errata, and examples for the rest of the book. This feature is designed to save you some typing time when your fingers start to cramp, but don’t abuse it: You gain a better understanding of C# when you enter the programs yourself and then use them as test beds for your explorations and experiments in C#.
Conventions Used in This Book
Throughout this book, we use several conventions to help you get your bearings. Terms that aren’t “real words,” such as the names of program variables, appear in this font to minimize confusion. Program listings are offset from the text this way:
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.
When you see a command arrow, as in the instruction “Choose File⇒Open With⇒Notepad,” you simply choose the File menu option. Then, from the menu that appears, choose Open With. Finally, from the resulting submenu, choose Notepad.
About this book’s Web site
Two main Web sites expand on the content in this book.
♦ At csharp102.info, you can find support for the original C# For Dummies book as well as a host of bonus material. A set of utilities is also included. We’ve used the SharpDevelop utility enough to know that it can handle the task of writing almost any program example 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 created from your lovely C# source code. The NUnit testing tool, wildly popular among C# programmers, makes testing your code easy, whether it’s in Visual Studio or SharpDevelop.
♦ At csharpfordummies.net, you can find the source code for all projects in this book, updated for Visual Studio 2010. We give you a set of links to other resources and a (short, we hope) list of any errata found in this book. You can also contact the authors at this site.
Additionally, you can find access to both sites at this book’s companion Web site — check out www.dummies.com/go/csharp2010aiofd.
If you encounter a situation that you can’t figure out, check the Frequently Asked Questions (FAQ) list at the original Web site for the C# For Dummies book, at csharp102.info.
In addition, both sites include bonus chapters, a list of any mistakes that may have crept into the book, and other material on C# and programming that you may find useful. Finally, you can find links to the authors’ e-mail addresses, in case you can’t find the answer to your question on the site.
Where to Go from Here
Obviously, your first step is to figure out the C# language — ideally, by using C# 2010 All-in-One For Dummies, of course. You may want to give yourself a few months of practice in writing simple C# programs before taking 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 Bill’s house, garbage collection is quite deterministic: It’s every Wednesday morning.) Here’s a description of a few large C# sites:
♦ msdn.microsoft.com/vcsharp, the C# home page, directs you to all sorts of C# and .NET resources.
♦ blogs.msdn.com/csharpfaq is a C# blog with Frequently Asked Questions.
♦ msdn.microsoft.com/vcsharp/team/blogs is composed of the personal blogs of C# team members.
♦ www.c-sharpcorner.com and www.codeproject.com are two major C# sites that have articles, blogs, code, job information, and other C#-related resources.
Book I
Basics of C# Programming
Tausende von E-Books und Hörbücher
Ihre Zahl wächst ständig und Sie haben eine Fixpreisgarantie.
Sie haben über uns geschrieben: