Microsoft .NET Development Series

John Montgomery, Series Advisor
Don Box, Series Advisor
Brad Abrams, Series Advisor

The award-winning Microsoft .NET Development Series was established in 2002 to provide professional developers with the most comprehensive and practical coverage of the latest .NET technologies. It is supported and developed by the leaders and experts of Microsoft development technologies, including Microsoft architects, MVPs, and leading industry luminaries. Books in this series provide a core resource of information and understanding every developer needs to write effective applications.

Titles in the Series

Brad Abrams, .NET Framework Standard Library Annotated Reference Volume 1: Base Class Library and Extended Numerics Library, 978-0-321-15489-7

Brad Abrams and Tamara Abrams, .NET Framework Standard Library Annotated Reference, Volume 2: Networking Library, Reflection Library, and XML Library, 978-0-321-19445-9

Chris Anderson, Essential Windows Presentation Foundation (WPF), 978-0-321-37447-9

Bob Beauchemin and Dan Sullivan, A Developer’s Guide to SQL Server 2005, 978-0-321-38218-4

Adam Calderon, Joel Rumerman, Advanced ASP.NET AJAX Server Controls: For .NET Framework 3.5, 978-0-321-51444-8

Eric Carter and Eric Lippert, Visual Studio Tools for Office: Using C# with Excel, Word, Outlook, and InfoPath, 978-0-321-33488-6

Eric Carter and Eric Lippert, Visual Studio Tools for Office: Using Visual Basic 2005 with Excel, Word, Outlook, and InfoPath, 978-0-321-41175-4

Steve Cook, Gareth Jones, Stuart Kent, Alan Cameron Wills, Domain-Specific Development with Visual Studio DSL Tools, 978-0-321-39820-8

Krzysztof Cwalina and Brad Abrams, Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries, Second Edition, 978-0-321-54561-9

Joe Duffy, Concurrent Programming on Windows, 978-0-321-43482-1

Sam Guckenheimer and Juan J. Perez, Software Engineering with Microsoft Visual Studio Team System, 978-0-321-27872-2

Anders Hejlsberg, Mads Torgersen, Scott Wiltamuth, Peter Golde, The C# Programming Language, Third Edition, 978-0-321-56299-9

Alex Homer and Dave Sussman, ASP.NET 2.0 Illustrated, 978-0-321-41834-0

Joe Kaplan and Ryan Dunn, The .NET Developer’s Guide to Directory Services Programming, 978-0-321-35017-6

Mark Michaelis, Essential C# 3.0: For .NET Framework 3.5, 978-0-321-53392-0

James S. Miller and Susann Ragsdale, The Common Language Infrastructure Annotated Standard, 978-0-321-15493-4

Christian Nagel, Enterprise Services with the .NET Framework: Developing Distributed Business Solutions with .NET Enterprise Services, 978-0-321-24673-8

Brian Noyes, Data Binding with Windows Forms 2.0: Programming Smart Client Data Applications with .NET, 978-0-321-26892-1

Brian Noyes, Smart Client Deployment with ClickOnce: Deploying Windows Forms Applications with ClickOnce, 978-0-321-19769-6

Fritz Onion with Keith Brown, Essential ASP.NET 2.0, 978-0-321-23770-5

Steve Resnick, Richard Crane, Chris Bowen, Essential Windows Communication Foundation: For .NET Framework 3.5, 978-0-321-44006-8

Scott Roberts and Hagen Green, Designing Forms for Microsoft Office InfoPath and Forms Services 2007, 978-0-321-41059-7

Neil Roodyn, eXtreme .NET: Introducing eXtreme Programming Techniques to .NET Developers, 978-0-321-30363-9

Chris Sells and Michael Weinhardt, Windows Forms 2.0 Programming, 978-0-321-26796-2

Dharma Shukla and Bob Schmidt, Essential Windows Workflow Foundation, 978-0-321-39983-0

Guy Smith-Ferrier, .NET Internationalization: The Developer’s Guide to Building Global Windows and Web Applications, 978-0-321-34138-9

Will Stott and James Newkirk, Visual Studio Team System: Better Software Development for Agile Teams, 978-0-321-41850-0

Paul Yao and David Durant, .NET Compact Framework Programming with C#, 978-0-321-17403-1

Paul Yao and David Durant, .NET Compact Framework Programming with Visual Basic .NET, 978-0-321-17404-8

For more information go to informit.com/msdotnetseries/

The C# Programming Language

Third Edition

Anders Hejlsberg
Mads Torgersen
Scott Wiltamuth
Peter Golde

Image  Addison-Wesley

Upper Saddle River, NJ  •  Boston  •  Indianapolis  •  San Francisco
New York  •  Toronto  •  Montreal  •  London  •  Munich  •  Paris  •  Madrid
Capetown  •  Sydney  •  Tokyo  •  Singapore  •  Mexico City

Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed with initial capital letters or in all capitals.

The .NET logo is either a registered trademark or trademark of Microsoft Corporation in the United States and/or other countries and is used under license from Microsoft.

Microsoft, Windows, Visual Basic, Visual C#, and Visual C++ are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A. and/or other countries/regions.

The authors and publisher have taken care in the preparation of this book, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein.

The publisher offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales, which may include electronic versions and/or custom covers and content particular to your business, training goals, marketing focus, and branding interests. For more information, please contact:

        U.S. Corporate and Government Sales
        (800) 382-3419
        [email protected]

For sales outside the United States please contact:

        International Sales
        [email protected]

Visit us on the Web: informit.com/aw

Library of Congress Cataloging-in-Publication Data

The C# programming language / Anders Hejlsberg… [et al.].—3rd ed.
    p. cm.
 Rev. ed of: The C# programming language / Anders Hejlsberg, Scott
Wiltamuth, Peter Golde, 2nd ed. 2006.
 Includes bibliographical references and index.
 ISBN 978-0-321-56299-9 (alk. paper)
 1. C# (Computer program language) I. Hejlsberg, Anders.

QA76.73.C154H45 2008
005.13'3—dc22

2008030025

Copyright © 2009 Microsoft Corporation

All rights reserved. Printed in the United States of America. This publication is protected by copyright, and permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. For information regarding permissions, write to:

        Pearson Education, Inc
        Rights and Contracts Department
        501 Boylston Street, Suite 900
        Boston, MA 02116
        Fax (617) 671-3447

ISBN-13: 978-0-321-56299-9
ISBN-10:    0-321-56299-2
Text printed in the United States on recycled paper at Courier in Westford, Massachusetts.
Second printing, January 2009

Contents

Foreword

Preface

About the Authors

About the Annotators

1   Introduction

1.1    Hello, World

1.2    Program Structure

1.3    Types and Variables

1.4    Expressions

1.5    Statements

1.6    Classes and Objects

1.7    Structs

1.8    Arrays

1.9    Interfaces

1.10   Enums

1.11   Delegates

1.12   Attributes

2   Lexical Structure

2.1    Programs

2.2    Grammars

2.3    Lexical Analysis

2.4    Tokens

2.5    Preprocessing Directives

3   Basic Concepts

3.1    Application Start-Up

3.2    Application Termination

3.3    Declarations

3.4    Members

3.5    Member Access

3.6    Signatures and Overloading

3.7    Scopes

3.8    Namespace and Type Names

3.9    Automatic Memory Management

3.10   Execution Order

4   Types

4.1    Value Types

4.2    Reference Types

4.3    Boxing and Unboxing

4.4    Constructed Types

4.5    Type Parameters

4.6    Expression Tree Types

5   Variables

5.1    Variable Categories

5.2    Default Values

5.3    Definite Assignment

5.4    Variable References

5.5    Atomicity of Variable References

6   Conversions

6.1    Implicit Conversions

6.2    Explicit Conversions

6.3    Standard Conversions

6.4    User-Defined Conversions

6.5    Anonymous Function Conversions

6.6    Method Group Conversions

7   Expressions

7.1    Expression Classifications

7.2    Operators

7.3    Member Lookup

7.4    Function Members

7.5    Primary Expressions

7.6    Unary Operators

7.7    Arithmetic Operators

7.8    Shift Operators

7.9    Relational and Type-Testing Operators

7.10   Logical Operators

7.11   Conditional Logical Operators

7.12   The Null Coalescing Operator

7.13   Conditional Operator

7.14   Anonymous Function Expressions

7.15   Query Expressions

7.16   Assignment Operators

7.17   Expressions

7.18   Constant Expressions

7.19    Boolean Expressions

8   Statements

8.1    End Points and Reachability

8.2    Blocks

8.3    The Empty Statement

8.4    Labeled Statements

8.5    Declaration Statements

8.6    Expression Statements

8.7    Selection Statements

8.8    Iteration Statements

8.9    Jump Statements

8.10   The try Statement

8.11   The checked and unchecked Statements

8.12   The lock Statement

8.13   The using Statement

8.14   The yield Statement

9   Namespaces

9.1    Compilation Units

9.2    Namespace Declarations

9.3    Extern Aliases

9.4    Using Directives

9.5    Namespace Members

9.6    Type Declarations

9.7    Namespace Alias Qualifiers

10 Classes

10.1    Class Declarations

10.2    Partial Types

10.3    Class Members

10.4    Constants

10.5    Fields

10.6    Methods

10.7    Properties

10.8    Events

10.9    Indexers

10.10    Operators

10.11    Instance Constructors

10.12    Static Constructors

10.13    Destructors

10.14    Iterators

11 Structs

11.1    Struct Declarations

11.2    Struct Members

11.3    Class and Struct Differences

11.4    Struct Examples

12 Arrays

12.1    Array Types

12.2    Array Creation

12.3    Array Element Access

12.4    Array Members

12.5    Array Covariance

12.6    Array Initializers

13 Interfaces

13.1    Interface Declarations

13.2    Interface Members

13.3    Fully Qualified Interface Member Names

13.4    Interface Implementations

14 Enums

14.1    Enum Declarations

14.2    Enum Modifiers

14.3    Enum Members

14.4    The System.Enum Type

14.5    Enum Values and Operations

15 Delegates

15.1    Delegate Declarations

15.2    Delegate Compatibility

15.3    Delegate Instantiation

15.4    Delegate Invocation

16 Exceptions

16.1    Causes of Exceptions

16.2    The System.Exception Class

16.3    How Exceptions Are Handled

16.4    Common Exception Classes

17 Attributes

17.1    Attribute Classes

17.2    Attribute Specification

17.3    Attribute Instances

17.4    Reserved Attributes

17.5    Attributes for Interoperation

18 Unsafe Code

18.1    Unsafe Contexts

18.2    Pointer Types

18.3    Fixed and Moveable Variables

18.4    Pointer Conversions

18.5    Pointers in Expressions

18.6    The fixed Statement

18.7    Fixed-Size Buffers

18.8    Stack Allocation

18.9    Dynamic Memory Allocation

A  Documentation Comments

A.1  Introduction

A.2.  Recommended Tags

A.3  Processing the Documentation File

A.4.  An Example

B  Grammar

B.1  Lexical Grammar

B.2  Syntactic Grammar

B.3  Grammar Extensions for Unsafe Code

C  References

Index

Foreword

It’s been eight years since the launch of .NET in the summer of 2000. For me, the significance of .NET was the one–two combination of managed code for local execution and XML messaging for program-to-program communication. What wasn’t obvious to me at the time was how important C# would be.

From the inception of .NET, C# has provided the primary means by which developers understand and interact with .NET. Ask the average .NET developer the difference between a value type and a reference type, and he or she will quickly say “struct versus class,” not “types that derive from System.ValueType versus those that don’t.” Why? Because people use languages, not APIs, to communicate their ideas and intention to the runtime and, more importantly, to one another.

It’s difficult to overstate how important having a great language has been to the success of the platform at large. C# was initially important to establish the baseline for how people think about .NET. It’s proven even more important as .NET has evolved, and features such as iterators and true closures (also known as anonymous methods) have been introduced to developers as purely language features implemented by the C# compiler, not as features native to the platform. The fact that C# is a vital center of innovation for .NET became even more apparent with the release of C# 3.0, which introduced standardized query operators, compact lambda expressions, extension methods, and runtime access to expression trees—again, all driven out of the language and the compiler.

It’s hard to talk about C# without also talking about its inventor and constant shepherd, Anders Hejlsberg. I had the distinct pleasure of participating in the recurring C# design meetings for a few months during the C# 3.0 design cycle, and it was enlightening watching Anders at work. His instincts for knowing what developers will and will not like is truly world class—yet at the same time, Anders is extremely inclusive of his design team and manages to get the best design possible.

With C# 3.0 in particular, Anders had an uncanny ability to take key ideas from the functional language community and make them accessible to a very broad audience. This is no trivial feat. Guy Steele once said of Java, “We were not out to win over the Lisp programmers; we were after the C++ programmers. We managed to drag a lot of them about halfway to Lisp.” When I look at C# 3.0, I know that C# has managed to drag at least one C++ developer (me) most of the rest of the way.

As good as C# is, people still need a document written in both natural language (English, in this case) and some formalism (BNF) to grok the subtleties and ensure that we’re all speaking the same C#. The book you hold in your hands is that document. Based on my own experience, I can safely say that every .NET developer who reads it will have at least one “aha” moment and will be a better developer for it.

Enjoy.

Don Box
July 2008

Preface

The C# project started almost ten years ago, in December 1998, with the goal of creating a simple, modern, object-oriented, and type-safe programming language for the new and yet-to-be-named .NET platform. Since then, C# has come a long way. The language is now in use by more than one million programmers, and it has been released in three versions, each of which added several major new features.

This book, too, is in its third edition. A complete technical specification of the C# programming language, the third edition differs in several ways from the first two. Most notably, of course, it has been updated to cover all the new features of C# 3.0, including object and collection initializers, anonymous types, lambda expressions, query expressions, and partial methods. Most of these features are motivated by support for a more functional and declarative style of programming and, in particular, for Language Integrated Query (LINQ), which offers a unified approach to data querying across different kinds of data sources. LINQ, in turn, builds heavily on some of the features that were introduced in C# 2.0, including generics, iterators, and partial types.

Another change in the third edition is that the specification has been thoroughly reorganized. In the second edition of this book, the features introduced in C# 2.0 were described separately from the original C# 1.0 features. With a third helping of new features, this approach did not scale—the utility of the book would be impaired by the reader’s need to correlate information from three different parts. Instead, the material is now organized by topic, with features from all three language versions presented together in an integrated manner.

A final but important departure from earlier editions is the inclusion of annotations in the text. We are very fortunate to be able to provide insightful guidance, background, and perspective from some of the world’s leading experts in C# and .NET in the form of annotations throughout the book. We are very happy to see the annotations complement the core material and help the C# features spring to life.

Many people have been involved in the creation of the C# language. The language design team for C# 1.0 consisted of Anders Hejlsberg, Scott Wiltamuth, Peter Golde, Peter Sollich, and Eric Gunnerson. For C# 2.0, the language design team consisted of Anders Hejlsberg, Peter Golde, Peter Hallam, Shon Katzenberger, Todd Proebsting, and Anson Horton. Furthermore, the design and implementation of generics in C# and the .NET Common Language Runtime are based on the “Gyro” prototype built by Don Syme and Andrew Kennedy of Microsoft Research. C# 3.0 was designed by Anders Hejlsberg, Peter Hallam, Shon Katzenberger, Dinesh Kulkarni, Erik Meijer, Mads Torgersen, and Matt Warren.

It is impossible to acknowledge the many people who have influenced the design of C#, but we are nonetheless grateful to all of them. Nothing good gets designed in a vacuum, and the constant feedback we receive from our large and enthusiastic community of developers is invaluable.

C# has been, and continues to be, one of the most challenging and exciting projects on which we’ve worked. We hope you enjoy using C# as much as we enjoyed creating it.

Anders Hejlsberg
Mads Torgersen
Scott Wiltamuth
Seattle, Washington
July 2008

About the Authors

Anders Hejlsberg is a programming legend. He is the architect of the C# language and a Microsoft Technical Fellow. He joined Microsoft in 1996, following a 13-year career at Borland, where he was the chief architect of Delphi and Turbo Pascal.

Mads Torgersen is a senior program manager at Microsoft. As the program manager for the C# language, he runs the C# language design meetings and maintains the C# language specification. Prior to joining Microsoft in 2005, Mads was an associate professor at the University of Aarhus, teaching and researching object-oriented programming languages. There, he led the group that designed and implemented generic wildcards for the Java Programming Language.

Scott Wiltamuth is partner program manager for Visual Studio. While at Microsoft, he has worked on a wide range of developer-oriented projects, including Visual Basic, VBScript, JScript, Visual J++, and Visual C#. Scott is one of the designers of the C# language, and holds bachelor’s and master’s degrees in computer science from Stanford University.

Before leaving Microsoft, Peter Golde served as the lead developer of Microsoft’s C# compiler. As the primary Microsoft representative on the ECMA committee that standardized C#, he led the implementation of the compiler and worked on the language design.

About the Annotators

Brad Abrams was a founding member of both the Common Language Runtime and .NET Framework teams at Microsoft Corporation. He has been designing part of the .NET Framework since 1998 and is currently the group program manager for Microsoft’s UI Framework and Services team. Find recent musings from Brad on his blog at http://blogs.msdn.com/BradA.

Joseph Albahari is coauthor of C# 3.0 in a Nutshell (O’Reilly, 2007), C# 3.0 Pocket Reference (O’Reilly, 2008), and LINQ Pocket Reference (O’Reilly, 2008). He has 17 years of experience as a senior developer and software architect in the health, education, and telecommunication industries, and is the author of LINQPad, the utility for interactively querying databases in LINQ.

Krzysztof Cwalina is a program manager on the .NET Framework team at Microsoft Corporation. He started his career at Microsoft designing APIs for the first release of the Framework. Currently, he is leading the effort to develop, promote, and apply the design guidelines to the .NET Framework. He is a coauthor of Framework Design Guidelines (Addison-Wesley, 2005). Reach him at his blog at http://blogs.msdn.com/kcwalina.

Don Box is a distinguished engineer at Microsoft, working on declarative languages and tools to simplify developing applications and services, and is involved in creating languages, frameworks, and end-to-end experiences to help people translate their intentions and desires for software into a machine readable and executable form. Don is a respected writer on software development topics, serving as a series editor on the Microsoft .NET Development Series (Addison-Wesley) and as a contributing editor to C++ Report, Microsoft Systems Journal (MSJ), and MSDN Magazine.

Jesse Liberty (“Silverlight Geek”) is a Microsoft senior program manager and the author of numerous best-selling books, including O’Reilly Media’s forthcoming Programming Silverlight 2 and Programming C# 3.0. Jesse has more than two decades of programming experience. He can be reached at www.JesseLiberty.com.

Eric Lippert is a senior developer on the C# compiler team at Microsoft Corporation. He has worked on the design and implementation of the Visual Basic, VBScript, Jscript, and C# languages and Visual Studio Tools for Office. His blog about all those topics and more can be found at http://blogs.msdn.com/EricLippert.

Fritz Onion is a founding partner of Pluralsight, a .NET developer training company. Fritz leads Pluralsight’s Web development curriculum, and teaches ASP.NET, Ajax, and Silverlight around the world. He is the author of the highly acclaimed books Essential ASP.NET and Essential ASP.NET 2.0 (both from Addison-Wesley); he also writes articles for many leading developer journals. You can read Fritz’s blog at http://pluralsight.com/fritz.

Vladimir Reshetnikov is Microsoft MVP for Visual C#. He has more than six years of software development experience, and four years of experience in Microsoft .NET and C#.

Chris Sells is a Program Manager for the Connected Systems Division of Microsoft Corporation. Chris has written several books, including Programming WPF (O’Reilly, 2007), Windows Forms 2.0 Programming (Addison-Wesley, 2006), and ATL Internals (Addison-Wesley, 1999). In his free time, Chris hosts various conferences and makes a pest of himself on Microsoft’s internal product team discussion lists. More information about Chris, and his various projects, is available at www.sellsbrothers.com.

Bill Wagner is the founder of SRT Solutions, a Microsoft Regional Director, and a C# MVP. He is the author of Effective C# (Addison-Wesley, 2005), and More Effective C# (Addison-Wesley, 2009), a columnist for Visual Studio Magazine, and a contributor to the C# Developer Center on MSDN.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset