Tải bản đầy đủ (.pdf) (884 trang)

programming c# 5.0

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (19.38 MB, 884 trang )

Ian Griffiths
Programming C# 5.0
ISBN: 978-1-449-32041-6
[LSI]
Programming C# 5.0
by Ian Griffiths
Copyright © 2013 Ian Griffiths. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are
also available for most titles (). For more information, contact our corporate/
institutional sales department: 800-998-9938 or
Editor: Rachel Roumeliotis
Production Editor: Kristen Borg
Copyeditor: Rachel Monaghan
Proofreader: Linley Dolby
Indexer: Ellen Troutman
Cover Designer: Karen Montgomery
Interior Designer: David Futato
Illustrator: Rebecca Demarest
October 2012: First Edition
Revision History for the First Edition:
2012-10-10 First release
See for release details.
Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly
Media, Inc.
Programming C# 5.0, the image of an African crowned crane, and related trade dress are trade
marks of O’Reilly Media, Inc.
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 O’Reilly Media, Inc., was aware of a trade
mark claim, the designations have been printed in caps or initial caps.
While every precaution has been taken in the preparation of this book, the publisher and author assume no
responsibility for errors or omissions, or for damages resulting from the use of the information contained
herein.
I dedicate this book to my excellent wife Deborah, and to my wonderful daughter, Hazel,
who arrived while this book was a work in progress.

Table of Contents
Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii
1.
Introducing C#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Why C#? 1
Why Not C#? 3
C#’s Defining Features 5
Managed Code and the CLR 7
Generality Trumps Specialization 9
Asynchronous Programming 10
Visual Studio 10
Anatomy of a Simple Program 13
Adding a Project to an Existing Solution 15
Referencing One Project from Another 15
Writing a Unit Test 17
Namespaces 20
Classes 24
Program Entry Point 25
Unit Tests 26
Summary 27
2.
Basic Coding in C#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

Local Variables 30
Scope 35
Statements and Expressions 39
Statements 39
Expressions 40
Comments and Whitespace 46
Preprocessing Directives 48
Compilation Symbols 48
#error and #warning 49
v
#line 50
#pragma 50
#region and #endregion 51
Intrinsic Data Types 51
Numeric Types 52
Booleans 61
Strings and Characters 62
Object 62
Operators 62
Flow Control 68
Boolean Decisions with if Statements 68
Multiple Choice with switch Statements 70
Loops: while and do 72
C-Style for Loops 73
Collection Iteration with foreach Loops 75
Summary 76
3. Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
Classes 77
Static Members 80
Static Classes 82

Reference Types 83
Structs 89
When to Write a Value Type 93
Members 98
Fields 98
Constructors 100
Methods 108
Properties 114
Indexers 117
Operators 119
Events 122
Nested Types 122
Interfaces 124
Enums 126
Other Types 129
Anonymous Types 129
Partial Types and Methods 130
Summary 131
4.
Generics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
Generic Types 134
vi | Table of Contents
Constraints 136
Type Constraints 137
Reference Type Constraints 139
Value Type Constraints 142
Multiple Constraints 142
Zero-Like Values 143
Generic Methods 144
Type Inference 145

Inside Generics 145
Summary 147
5.
Collections. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
Arrays 149
Array Initialization 153
Variable Argument Count with the params Keyword 154
Searching and Sorting 155
Multidimensional Arrays 162
Copying and Resizing 166
List<T> 167
List and Sequence Interfaces 170
Implementing Lists and Sequences 174
Iterators 175
Collection<T> 179
ReadOnlyCollection<T> 180
Dictionaries 181
Sorted Dictionaries 184
Sets 185
Queues and Stacks 186
Linked Lists 187
Concurrent Collections 188
Tuples 189
Summary 190
6.
Inheritance. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
Inheritance and Conversions 192
Interface Inheritance 194
Generics 195
Covariance and Contravariance 196

System.Object 202
The Ubiquitous Methods of object 202
Accessibility and Inheritance 203
Virtual Methods 204
Table of Contents | vii
Abstract Methods 206
Sealed Methods and Classes 213
Accessing Base Members 214
Inheritance and Construction 215
Special Base Types 220
Summary 221
7.
Object Lifetime. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
Garbage Collection 224
Determining Reachability 225
Accidentally Defeating the Garbage Collector 227
Weak References 230
Reclaiming Memory 234
Garbage Collector Modes 240
Accidentally Defeating Compaction 242
Forcing Garbage Collections 245
Destructors and Finalization 246
Critical Finalizers 250
IDisposable 250
Optional Disposal 257
Boxing 257
Boxing Nullable<T> 262
Summary 263
8.
Exceptions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265

Exception Sources 267
Exceptions from APIs 268
Exceptions from Your Code 270
Failures Detected by the Runtime 271
Handling Exceptions 272
Exception Objects 273
Multiple catch Blocks 274
Nested try Blocks 275
finally Blocks 277
Throwing Exceptions 278
Rethrowing Exceptions 279
Failing Fast 282
Exception Types 283
Custom Exceptions 285
Unhandled Exceptions 288
Debugging and Exceptions 290
Asynchronous Exceptions 292
viii | Table of Contents
Summary 294
9. Delegates, Lambdas, and Events. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
Delegate Types 296
Creating a Delegate 297
Multicast Delegates 301
Invoking a Delegate 302
Common Delegate Types 305
Type Compatibility 306
Behind the Syntax 310
Inline Methods 313
Captured Variables 316
Lambdas and Expression Trees 323

Events 324
Standard Event Delegate Pattern 326
Custom Add and Remove Methods 327
Events and the Garbage Collector 330
Events Versus Delegates 332
Delegates Versus Interfaces 333
Summary 333
10.
LINQ. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
Query Expressions 336
How Query Expressions Expand 339
Supporting Query Expressions 341
Deferred Evaluation 345
LINQ, Generics, and IQueryable<T> 348
Standard LINQ Operators 350
Filtering 352
Select 354
SelectMany 357
Ordering 360
Containment Tests 362
Specific Items and Subranges 364
Aggregation 368
Set Operations 372
Whole-Sequence, Order-Preserving Operations 373
Grouping 374
Joins 379
Conversion 381
Sequence Generation 386
Other LINQ Implementations 386
Table of Contents | ix

Entity Framework 387
LINQ to SQL 387
WCF Data Services Client 388
Parallel LINQ (PLINQ) 388
LINQ to XML 388
Reactive Extensions 388
Summary 389
11.
Reactive Extensions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
Rx and .NET Versions 393
Fundamental Interfaces 395
IObserver<T> 396
IObservable<T> 397
Publishing and Subscribing with Delegates 404
Creating an Observable Source with Delegates 404
Subscribing to an Observable Source with Delegates 407
Sequence Builders 409
Empty 409
Never 409
Return 409
Throw 410
Range 410
Repeat 410
Generate 410
LINQ Queries 411
Grouping Operators 414
Join Operators 415
SelectMany Operator 420
Aggregation and Other Single-Value Operators 420
Concat Operator 422

Rx Query Operators 422
Merge 423
Windowing Operators 424
The Scan Operator 431
The Amb Operator 432
DistinctUntilChanged 433
Schedulers 434
Specifying Schedulers 434
Built-in Schedulers 437
Subjects 438
Subject<T> 438
BehaviorSubject<T> 440
x | Table of Contents
ReplaySubject<T> 440
AsyncSubject<T> 441
Adaptation 441
IEnumerable<T> 441
.NET Events 443
Asynchronous APIs 445
Timed Operations 447
Interval 447
Timer 449
Timestamp 449
TimeInterval 450
Throttle 451
Sample 451
Timeout 451
Windowing Operators 451
Delay 452
DelaySubscription 453

Summary 453
12.
Assemblies. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455
Visual Studio and Assemblies 455
Anatomy of an Assembly 456
.NET Metadata 457
Resources 457
Multifile Assemblies 457
Other PE Features 458
Type Identity 460
Loading Assemblies 462
Explicit Loading 465
The Global Assembly Cache 466
Assembly Names 468
Strong Names 468
Version 471
Culture 476
Processor Architecture 479
Portable Class Libraries 480
Packaged Deployment 482
Windows 8 UI–Style Apps 482
ClickOnce and XBAP 483
Silverlight and Windows Phone Apps 484
Protection 485
Table of Contents | xi
Summary 486
13. Reflection. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
Reflection Types 488
Assembly 490
Module 494

MemberInfo 495
Type and TypeInfo 498
MethodBase, ConstructorInfo, and MethodInfo 502
ParameterInfo 504
FieldInfo 505
PropertyInfo 505
EventInfo 505
Reflection Contexts 506
Summary 508
14. Dynamic Typing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 509
The dynamic Type 511
dynamic and Interoperability 513
Silverlight and Scriptable Objects 516
Dynamic .NET Languages 517
Inside Dynamic 518
Restrictions on the dynamic Type 518
Custom Dynamic Objects 520
ExpandoObject 523
Limitations of dynamic 523
Summary 526
15.
Attributes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 527
Applying Attributes 527
Attribute Targets 530
Compiler-Handled Attributes 531
CLR-Handled Attributes 536
Defining and Consuming Custom Attributes 543
Attribute Type 544
Retrieving Attributes 546
Summary 548

16.
Files and Streams. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 551
The Stream Class 552
Position and Seeking 554
Flushing 555
xii | Table of Contents
Copying 556
Length 556
Disposal 558
Asynchronous Operation 559
Concrete Stream Types 559
Windows 8 and IRandomAccessStream 560
Text-Oriented Types 563
TextReader and TextWriter 564
Concrete Reader and Writer Types 566
Encoding 568
Files and Directories 572
FileStream Class 573
File Class 576
Directory Class 579
Path Class 580
FileInfo, DirectoryInfo, and FileSystemInfo 582
Known Folders 583
Serialization 584
BinaryReader and BinaryWriter 585
CLR Serialization 585
Data Contract Serialization 589
XmlSerializer 592
Summary 593
17.

Multithreading. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 595
Threads 595
Threads, Variables, and Shared State 597
The Thread Class 603
The Thread Pool 605
Thread Affinity and SynchronizationContext 610
Synchronization 614
Monitors and the lock Keyword 615
SpinLock 621
Reader/Writer Locks 623
Event Objects 624
Barrier 627
CountdownEvent 628
Semaphores 628
Mutex 629
Interlocked 629
Lazy Initialization 632
Other Class Library Concurrency Support 634
Table of Contents | xiii
Tasks 635
The Task and Task<T> Classes 635
Continuations 639
Schedulers 641
Error Handling 642
Custom Threadless Tasks 643
Parent/Child Relationships 645
Composite Tasks 645
Other Asynchronous Patterns 646
Cancellation 647
Parallelism 648

The Parallel Class 648
Parallel LINQ 649
TPL Dataflow 650
Summary 650
18. Asynchronous Language Features. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 651
Asynchronous Keywords: async and await 652
Execution and Synchronization Contexts 656
Multiple Operations and Loops 657
Returning a Task 660
Applying async to Nested Methods 662
The await Pattern 662
Error Handling 667
Validating Arguments 669
Singular and Multiple Exceptions 670
Concurrent Operations and Missed Exceptions 672
Summary 673
19.
XAML. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 675
XAML-Based Frameworks 676
WPF 677
Silverlight 678
Windows Phone 7 680
Windows Runtime and Windows 8 UI–Style Apps 680
XAML Basics 682
XAML and XML Namespaces 683
Generated Classes and Codebehind 684
Child Elements 686
Property Elements 687
Event Handling 688
Threading 689

xiv | Table of Contents
Layout 690
Properties 691
Panels 697
ScrollViewer 707
Layout Events 707
Controls 709
Content Controls 709
Slider and ScrollBar Controls 713
Progress Controls 713
List Controls 715
Control Templates 716
UserControls 720
Text 720
Displaying Text 721
Editing Text 723
Data Binding 724
Data Templates 728
Graphics 731
Shapes 731
Bitmaps 732
Media 733
Styles 734
Summary 735
20.
ASP.NET. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 737
Razor 738
Expressions 739
Flow Control 741
Code Blocks 742

Explicitly Indicated Content 743
Page Classes and Objects 744
Using Other Components 745
Layout Pages 746
Start Pages 747
Web Forms 748
Server-Side Controls 748
Expressions 754
Code Blocks 754
Standard Page Objects 755
Page Classes and Objects 756
Using Other Components 756
Master Pages 757
Table of Contents | xv
MVC 759
Typical MVC Project Layout 759
Writing Models 766
Writing Views 768
Writing Controllers 770
Handling Additional Input 772
Generating Action Links 775
Routing 775
Summary 780
21. Interoperability. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 781
Calling Native Code 781
Marshaling 782
32-bit and 64-bit 790
Safe Handles 791
Security 793
Platform Invoke 793

Calling Convention 794
Text Handling 795
Entry Point Name 795
COM-Style Return Values 796
Win32 Error Handling 800
COM 800
RCW Lifetime 801
Metadata 803
Scripting 809
Windows Runtime 813
Metadata 813
Windows Runtime Types 813
Buffers 814
Unsafe Code 816
C++/CLI and the Component Extensions 818
Summary 818
Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 821
xvi | Table of Contents
Preface
C# is now well into its second decade. It has grown steadily in both power and size, but
Microsoft has always kept the essential characteristics intact—C# still feels like the same
language as was first unveiled back in 2000. Each new capability is designed to integrate
cleanly with the rest, enhancing the language without turning it into an incoherent bag
of miscellaneous features. This philosophy is evident in the most important new addi
tion to C#—its support for asynchronous programming. It has always been possible to
use asynchronous APIs in C#, but in the past, this tended to involve convoluted code.
In C# 5.0, you can write asynchronous code that looks almost exactly like normal code,
so instead of adding weight to the language, this new asynchronous programming sup
port makes things simpler.
Even though C# continues to be a fairly straightforward language at its heart, there is a

great deal more to say about it now than in its first incarnation. Successive editions of
this book have responded to the language’s progress with ever-increasing page counts,
but this latest edition does not merely try to cram in yet more details. It expects a some
what higher level of technical ability from its readers than before.
Who This Book Is For
I have written this book for experienced developers—I’ve been programming for years,
and I’ve set out to make this the book I would want to read if that experience had been
in other languages, and I were learning C# today. Whereas previous editions explained
some basic concepts such as classes, polymorphism, and collections, I am assuming that
readers will already know what these are. The early chapters still describe how C#
xvii
presents these common ideas, but the focus is on the details specific to C#, rather than
the broad concepts. So if you have read previous editions of this book, you will find that
this one spends less time on these basic concepts, and goes into rather more detail on
everything else.
Conventions Used in This Book
The following typographical conventions are used in this book:
Italic
Indicates new terms, URLs, email addresses, filenames, and file extensions.
Constant width
Used for program listings, as well as within paragraphs to refer to program elements
such as variable or function names, databases, data types, environment variables,
statements, and keywords.
Constant width bold
Shows commands or other text that should be typed literally by the user.
Constant width italic
Shows text that should be replaced with user-supplied values or by values deter
mined by context.
This icon signifies a tip, suggestion, or general note.
This icon indicates a warning or caution.

Using Code Examples
This book is here to help you get your job done. In general, you may use the code in this
book in your programs and documentation. You do not need to contact us for permis
sion unless you’re reproducing a significant portion of the code. For example, writing a
program that uses several chunks of code from this book does not require permission.
Selling or distributing a CD-ROM of examples from O’Reilly books does require per
mission. Answering a question by citing this book and quoting example code does not
require permission. Incorporating a significant amount of example code from this book
into your product’s documentation does require permission.
xviii | Preface
We appreciate, but do not require, attribution. An attribution usually includes the title,
author, publisher, and ISBN. For example: “Programming C# 5.0 by Ian Griffiths (O’Reil
ly). Copyright 2013 by Ian Griffiths, 978-1-449-32041-6.”
If you feel your use of code examples falls outside fair use or the permission given above,
feel free to contact us at
Safari® Books Online
Safari Books Online (www.safaribooksonline.com) is an on-demand
digital library that delivers expert content in both book and video
form from the world’s leading authors in technology and business.
Technology professionals, software developers, web designers, and business and creative
professionals use Safari Books Online as their primary resource for research, problem
solving, learning, and certification training.
Safari Books Online offers a range of product mixes and pricing programs for organi
zations, government agencies, and individuals. Subscribers have access to thousands of
books, training videos, and prepublication manuscripts in one fully searchable database
from publishers like O’Reilly Media, Prentice Hall Professional, Addison-Wesley Pro
fessional, Microsoft Press, Sams, Que, Peachpit Press, Focal Press, Cisco Press, John
Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe Press, FT
Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, Course Technol
ogy, and dozens more. For more information about Safari Books Online, please visit us

online.
How to Contact Us
Please address comments and questions concerning this book to the publisher:
O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)
We have a web page for this book, where we list errata, examples, and any additional
information. You can access this page at />To comment or ask technical questions about this book, send email to bookques

Preface | xix
For more information about our books, courses, conferences, and news, see our website
at .
Find us on Facebook: />Follow us on Twitter: />Watch us on YouTube: />Acknowledgments
Many thanks to the book’s official technical reviewers: Glyn Griffiths, Alex Turner, and
Chander Dhall. I’d also like to give a big thank you to those who reviewed individual
chapters, or otherwise offered help or information that improved this book: Brian Ras
mussen, Eric Lippert, Andrew Kennedy, Daniel Sinclair, Brian Randell, Mike Woodring,
Mike Taulty, Mary Jo Foley, Bart De Smet, and Stephen Toub.
Thank you to everyone at O’Reilly whose work brought this book into existence. In
particular, thanks to Rachel Roumeliotis for encouraging me to write this new edition,
and thank you also to Kristen Borg, Rachel Monaghan, Gretchen Giles, and Yasmina
Greco for your excellent support. Finally, thank you to John Osborn, for taking me on
as an O’Reilly author back when I wrote my first book.
xx | Preface
1. New to Windows, at any rate.
CHAPTER 1
Introducing C#

The C# programming language (pronounced “see sharp”) can be used for many kinds
of applications, including websites, desktop applications, games, phone apps, and
command-line utilities. C# has been center stage for Windows developers for about a
decade now, so when Microsoft announced that Windows 8 would introduce a new
1
style of application, optimized for touch-based interaction on tablets, it was no surprise
that C# was one of the four languages to offer full support from the start for these
applications (the others being C++, JavaScript, and Visual Basic).
Although Microsoft invented C#, the language and its runtime are documented by the
standards body ECMA, enabling anyone to implement C#. This is not merely hypo
thetical. The open source Mono project ( provides tools
for building C# applications that run on Linux, Mac OS X, iOS, and Android.
Why C#?
Although there are many ways you can use C#, other languages are always an option.
Why might you choose C# over them? It will depend on what you need to do, and what
you like and dislike in a programming language. I find that C# provides considerable
power and flexibility, and works at a high enough level of abstraction that I don’t expend
vast amounts of effort on little details not directly related to the problems my programs
are trying to solve. (I’m looking at you, C++.)
1
Much of C#’s power comes from the range of programming techniques it supports. For
example, it offers object-oriented features, generics, and functional programming. It
supports both dynamic and static typing. It provides powerful list- and set-oriented
features, thanks to Language Integrated Query (LINQ). The most recent version of the
language adds intrinsic support for asynchronous programming.
Some of the most important benefits of using C# come from its runtime, which provides
services such as security sandboxing, runtime type checking, exception handling, thread
management, and perhaps its most important feature, automated memory manage
ment. The runtime provides a garbage collector that frees developers from much of the
work associated with recovering memory that the program is no longer using.

Of course, languages do not exist in a vacuum—high-quality libraries with a broad range
of features are essential. There are some elegant and academically beautiful languages
that are glorious right up until you want to do something prosaic, such as talking to a
database or determining where to store user settings. No matter how strong a set of
programming idioms a language offers, it also needs to provide full and convenient
access to the underlying platform’s services. C# is on very strong ground here, thanks
to the .NET Framework.
The .NET Framework encompasses both the runtime and the libraries that C# programs
use on Windows. The runtime part is called the Common Language Runtime (usually
abbreviated to CLR) because it supports not just C#, but any .NET language. Numerous
languages can run in .NET. Microsoft’s development environment, Visual Studio, pro
vides Visual Basic, F#, and .NET extensions for C++, for example, and there are open
source .NET-based implementations of Python and Ruby (called IronPython and Iron
Ruby, respectively). The CLR has a Common Type System (CTS) that enables code from
multiple languages to interoperate freely, which means that .NET libraries can usually
be used from any .NET language—F# can consume libraries written in C#, C# can use
Visual Basic libraries, and so on. The .NET Framework includes an extensive class li
brary. This library provides wrappers for many features of the underlying operating
system (OS), but it also provides a considerable amount of functionality of its own. It
contains over 10,000 classes, each with numerous members.
Some parts of the .NET Framework class library are specific to Win
dows. There are library features dedicated to building Windows desktop
applications, for example. However, other parts are more generic, such
as the HTTP client classes, which would be relevant on any operating
system. The ECMA specification for the runtime used by C# defines a
set of library features that are not dependent on any particular operating
system. The .NET Framework class library supports all these features,
of course, as well as offering Microsoft-specific ones.
2 | Chapter 1: Introducing C#
The libraries built into the .NET Framework are not the whole story—many other

frameworks provide their own .NET class libraries. SharePoint has an extensive .NET
application programming interface (API), for example. And libraries do not have to be
associated with frameworks. There’s a large ecosystem of .NET libraries, some com
mercial and some free and open source. There are mathematical utilities, parsing libra
ries, and user interface components, to name just a few.
Even if you get unlucky and need to use an OS feature that doesn’t have any .NET library
wrappers, C# offers various mechanisms for working with older style APIs, such as
Win32 and COM. Some aspects of the interoperability mechanisms are a little clunky,
and if you need to deal with an existing component, you might need to write a thin
wrapper that presents a more .NET-friendly face. (You can still write the wrapper in C#.
You’d just be putting the awkward interoperability details in one place, rather than letting
them pollute your whole codebase.) However, if you design a new COM component
carefully, you can make it straightforward to use directly from C#. Windows 8 introduces
a new kind of API for writing full-screen applications optimized for tablet computers,
an evolution of COM called
WinRT, and—unlike interoperability with older native
Windows APIs—using WinRT from C# feels very natural.
In summary, with C# we get a strong set of abstractions built into the language, a pow
erful runtime, and easy access to an enormous amount of library and platform func
tionality.
Why Not C#?
To understand a language, it’s useful to compare it with alternatives, so it’s worth looking
at some of the reasons you might choose some other language. C#’s nearest competitor
is arguably Visual Basic (VB), another native .NET language that offers most of the same
benefits as C#. The choice here is mostly a matter of syntax. C# is part of the C family
of languages, and if you are familiar with at least one language from that group (which
includes C, C++, Objective-C, Java, and JavaScript), you will feel instantly at home with
C#’s syntax. However, if you do not know any of those languages, but you are at home
with pre NET versions of Visual Basic, or with the scripting variants such as Microsoft
Office’s Visual Basic for Applications (VBA), then the .NET version of Visual Basic would

certainly be easier to learn.
Visual Studio offers another language designed specifically for the .NET Framework,
called F#. This is a very different language from C# and Visual Basic, and it seems to be
aimed mostly at calculation-intensive applications such as engineering, and the more
technical areas of finance. F# is primarily a functional programming language, with its
roots firmly in academia. (Its closest non NET relative is a programming language
called OCaml, which is popular in universities but has never been a commercial hit.) It
is good for expressing particularly complex computations, so if you’re working on ap
plications that spend much more of their time thinking than doing, F# may be for you.
Why Not C#? | 3

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×