Tutorial C# : Essential C# / PDF


Tutorial C# : Essential C# / PDF

Tutorial C# : Essential C# / PDF







Contents



1 Introducing C# 
Hello, World 2
Compiling and Running the Application 3
C# Syntax Fundamentals 4
Type Definition 7
Main 8
Statements and Statement Delimiters 10
Whitespace 11
Working with Variables 12
Data Types 13
Declaring a Variable 14
Assigning a Variable 14
Using a Variable 16
Console Input and Output 16
Getting Input from the Console 16
Writing Output to the Console 18
Comments 20
Managed Execution and the Common Language Infrastructure 23
Contents
Contents
C# and .NET Versioning 26
Common Intermediate Language and ILDASM 27
Summary 30

2 Data Types 
Fundamental Numeric Types 32
Integer Types 32
Floating-Point Types (float, double) 33
Decimal Type 34
Literal Values 35
More Fundamental Types 40
Boolean Type (bool) 40
Character Type (char) 41
Strings 43
null and void 51
null 51
The void Nontype 52
Categories of Types 55
Value Types 55
Reference Types 56
Nullable Modifier 57
Conversions between Data Types 58
Explicit Cast 58
Implicit Conversion 62
Type Conversion without Casting 62
Arrays 64
Declaring an Array 65
Instantiating and Assigning Arrays 66
Using an Array 70
Strings as Arrays 76
Common Errors 78
Summary 81

3 Operators and Control Flow
Operators 84
Plus and Minus Unary Operators (+, -) 84
Arithmetic Binary Operators (+, -, *, /, %) 85
Parenthesis Operator 92
Assignment Operators (+=, -=, *=, /=, %=) 93
Increment and Decrement Operators (++, --) 94
Constant Expressions (const) 98
Contents xiii
Introducing Flow Control 98
if Statement 102
Nested if 103
Code Blocks ({}) 105
Scope and Declaration Space 107
Boolean Expressions 109
Relational and Equality Operators 110
Logical Boolean Operators 111
Logical Negation Operator (!) 113
Conditional Operator (?) 113
Null Coalescing Operator (??) 114
Bitwise Operators (<<, >>, |, &, ^, ~) 115
Shift Operators (<<, >>, <<=, >>=) 116
Bitwise Operators (&, |, ^) 117
Bitwise Assignment Operators (&=, |=, ^=) 120
Bitwise Complement Operator (~) 120
Control Flow Statements, Continued 121
The while and do/while Loops 121
The for Loop 124
The foreach Loop 127
The switch Statement 130
Jump Statements 132
The break Statement 132
The continue Statement 135
The goto Statement 137
C# Preprocessor Directives 138
Excluding and Including Code (#if, #elif, #else, #endif) 140
Defining Preprocessor Symbols (#define, #undef) 141
Emitting Errors and Warnings (#error, #warning) 141
Turning Off Warning Messages (#pragma) 142
nowarn: Option 143
Specifying Line Numbers (#line) 143
Hints for Visual Editors (#region, #endregion) 144
Summary 145

4 Methods and Parameters 
Calling a Method 150
Namespace 152
Type Name 154
Scope 155
Method Name 155
Parameters 155
Contents
Method Return 155
Statement versus Method Call 156
Declaring a Method 157
Parameter Declaration 159
Method Return Declaration 159
The using Directive 161
Aliasing 164
Returns and Parameters on Main() 165
Parameters 168
Value Parameters 168
Reference Parameters (ref) 170
Output Parameters (out) 171
Parameter Arrays (params) 173
Recursion 176
Method Overloading 179
Optional Parameters 182
Basic Error Handling with Exceptions 186
Trapping Errors 187
Reporting Errors Using a throw Statement 196
Summary 199

5 Classes 
Declaring and Instantiating a Class 205
Instance Fields 209
Declaring an Instance Field 209
Accessing an Instance Field 210
Instance Methods 211
Using the this Keyword 213
Access Modifiers 220
Properties 222
Declaring a Property 223
Automatically Implemented Properties 225
Naming Conventions 227
Using Properties with Validation 228
Read-Only and Write-Only Properties 230
Access Modifiers on Getters and Setters 231
Properties as Virtual Fields 232
Properties and Method Calls Not Allowed as ref or out
Parameter Values 234
Constructors 236
Declaring a Constructor 237
Default Constructors 239
Object Initializers 239
Contents xv
Overloading Constructors 241
Constructor Chaining: Calling another
Constructor Using this 243
Static Members 247
Static Fields 248
Static Methods 251
Static Constructors 253
Static Properties 254
Static Classes 255
Extension Methods 256
Encapsulating the Data 258
const 258
readonly 259
Nested Classes 260
Partial Classes 262
Defining a Partial Class 263
Partial Methods 264
Summary 267

6 Inheritance 
Derivation 270
Casting between Base and Derived Types 272
private Access Modifier 275
protected Access Modifier 276
Extension Methods 278
Single Inheritance 278
Sealed Classes 281
Overriding the Base Class 281
virtual Modifier 282
new Modifier 286
sealed Modifier 291
base Member 291
Constructors 292
Abstract Classes 293
All Classes Derive from System.Object 299
Verifying the Underlying Type with the is Operator 301
Conversion Using the as Operator 302
Summary 303

7 Interfaces 
Introducing Interfaces 306
Polymorphism through Interfaces 307
Interface Implementation 312
Contents
Explicit Member Implementation 314
Implicit Member Implementation 315
Explicit versus Implicit Interface Implementation 316
Converting between the Implementing Class and Its
Interfaces 318
Interface Inheritance 318
Multiple Interface Inheritance 321
Extension Methods on Interfaces 322
Implementing Multiple Inheritance via Interfaces 323
Versioning 326
Interfaces Compared with Classes 328
Summary 329

8 Value Types 
Structs 332
Initializing structs 336
Using the default Operator 338
Inheritance and Interfaces with Value Types 338
Boxing 339
Enums 346
Type Compatibility between Enums 349
Converting between Enums and Strings 350
Enums as Flags 351
Summary 356

9 Well-Formed Types 
Overriding object Members 357
Overriding ToString() 358
Overriding GetHashCode() 358
Overriding Equals() 361
Guidelines for Implementing Equality 369
Operator Overloading 369
Comparison Operators (==, !=, <, >, <=, >=) 370
Binary Operators (+, -, *, /, %, &, |, ^, <<, >>) 371
Combining Assignment with Binary Operators (+=, -=, *=, /=, %=, &=…) 373
Conditional Logical Operators (&&, ||) 373
Unary Operators (+, -, !, ~, ++, --, true, false) 373
Conversion Operators 375
Guidelines for Conversion Operators 377
Referencing Other Assemblies 377
Changing the Assembly Target 378
Referencing an Assembly 379
Encapsulation of Types 379
Contents xvii
Defining Namespaces 382
Namespace Alias Qualifier 384
XML Comments 385
Associating XML Comments with Programming Constructs 386
Generating an XML Documentation File 388
Garbage Collection 390
Weak References 391
Resource Cleanup 393
Finalizers 393
Deterministic Finalization with the using Statement 395
Garbage Collection and Finalization 398
Resource Utilization and Finalization Guidelines 400
Lazy Initialization 400
Summary 403

10 Exception Handling 
Multiple Exception Types 405
Catching Exceptions 407
General Catch Block 409
Guidelines for Exception Handling 411
Defining Custom Exceptions 414
Summary 419

11 Generics 
C# without Generics 422
Introducing Generic Types 427
Using a Generic Class 427
Defining a Simple Generic Class 429
Benefits of Generics 430
Type Parameter Naming Guidelines 431
Generic Interfaces and Structs 432
Defining a Constructor and a Finalizer 434
Specifying a Default Value 435
Multiple Type Parameters 436
Arity in Abundance 437
Nested Generic Types 438
Constraints 439
Interface Constraints 442
Base Class Constraints 444
struct/class Constraints 445
Multiple Constraints 446
Constructor Constraints 446
Constraint Inheritance 447
Contents
Generic Methods 453
Type Inferencing 454
Specifying Constraints 455
Covariance and Contravariance 457
Enabling Covariance with the out Type Parameter Modifier in C# 4.0 458
Enabling Contravariance with the in Type Parameter Modifier in C# 4.0 460
Support for Parameter Covariance and Contravariance in Arrays 462
Generic Internals 463
Instantiating Generics Based on Value Types 464
Instantiating Generics Based on Reference Types 465
Summary 467

12 Delegates and Lambda Expressions 
Introducing Delegates 470
Defining the Scenario 470
Delegate Data Types 472
Delegate Internals 473
Defining a Delegate Type 474
Instantiating a Delegate 475
Anonymous Methods 480
System-Defined Delegates: Func<> 483
Lambda Expressions 486
Statement Lambdas 486
Expression Lambdas 489
Outer Variables 495
Expression Trees 498
Summary 506

13 Events 
Coding the Observer Pattern with Multicast Delegates 508
Defining Subscriber Methods 508
Defining the Publisher 510
Hooking Up the Publisher and Subscribers 511
Invoking a Delegate 512
Check for null 513
Delegate Operators 514
Sequential Invocation 516
Error Handling 519
Method Returns and Pass-by-Reference 522
Events 523
Why Events? 523
Declaring an Event 525
Coding Conventions 526
Contents xix
Generics and Delegates 528
Customizing the Event Implementation 532
Summary 533

14 Collection Interfaces with Standard Query Operators 
Anonymous Types and Implicitly Typed Local Variables 536
Anonymous Types 537
Implicitly Typed Local Variables (var) 538
More about Anonymous Types and Implicit Local Variables 540
Collection Initializers 543
What Makes a Class a Collection: IEnumerable 546
foreach with Arrays 546
foreach with IEnumerable 547
Do Not Modify Collections during foreach Iteration 552
Standard Query Operators 552
Filtering with Where() 556
Projecting with Select() 557
Counting Elements with Count() 561
Deferred Execution 562
Sorting with OrderBy() and ThenBy() 566
Performing an Inner Join with Join() 572
Grouping Results with GroupBy() 575
Implementing a One-to-Many Relationship with GroupJoin() 577
Calling SelectMany() 580
More Standard Query Operators 582
Summary 586

15 LINQ with Query Expressions 
Introducing Query Expressions 590
Projection 592
Filtering 598
Sorting 599
The Let Clause 600
Grouping 602
Query Continuation with into 605
Query Expressions as Method Invocations 608
Summary 609

16 Building Custom Collections 
More Collection Interfaces 612
IList versus IDictionary 614
IComparable 614
ICollection 616
Contents
Primary Collection Classes 617
List Collections: List 617
Dictionary Collections: Dictionary 622
Sorted Collections: SortedDictionary and
SortedList 626
Stack Collections: Stack 628
Queue Collections: Queue 629
Linked Lists: LinkedList 629
Providing an Index Operator 630
Returning Null or an Empty Collection 634
Iterators 634
Defining an Iterator 636
Iterator Syntax 636
Yielding Values from an Iterator 637
Iterators and State 639
More Iterator Examples 641
Placing a yield return within a Loop 643
Canceling Further Iteration: yield break 645
Creating Multiple Iterators in a Single Class 648
yield Statement Characteristics 649
Summary 650

17 Reflection, Attributes, and Dynamic Programming 
Reflection 652
Accessing Metadata Using System.Type 653
Member Invocation 655
Reflection on Generic Types 660
Attributes 663
Custom Attributes 666
Looking for Attributes 667
Initializing an Attribute through a Constructor 668
System.AttributeUsageAttribute 673
Named Parameters 674
Programming with Dynamic Objects 688
Invoking Reflection Using dynamic 689
dynamic Principles and Behaviors 690
Why Dynamic Binding? 694
Static Compilation versus Dynamic Programming 695
Implementing a Custom Dynamic Object 696
Summary 699
Contents xxi

18 Multithreading 
Running and Controlling a Separate Thread 706
ContinueWith() 711
Unhandled Exception Handling on Task 715
Canceling a Task 718
Long-Running Tasks 722
Disposing a Task 723
Executing Iterations in Parallel 724
Parallel Exception Handling with System.AggregateException 728
Canceling a Parallel Loop 729
Running LINQ Queries in Parallel 734
Canceling a PLINQ Query 736
Multithreading before .NET Framework 4 738
Asynchronous Operations with System.Threading.Thread 738
Thread Management 740
Thread Pooling 742
Unhandled Exceptions on the AppDomain 744
Summary 746

19 Synchronization and More Multithreading Patterns 
Synchronization 750
Synchronization Using Monitor 754
Using the lock Keyword 757
Choosing a lock Object 758
Why to Avoid Locking on this, typeof(type), and string 759
Declaring Fields as volatile 760
Using the System.Threading.Interlocked Class 761
Event Notification with Multiple Threads 763
Synchronization Design Best Practices 764
More Synchronization Types 766
Thread Local Storage 774
Timers 778
Asynchronous Programming Model 783
Calling the APM 784
Calling the APM Using TPL 791
Asynchronous Delegate Invocation 797
Passing Data to and from an Alternate Thread 799
Event-Based Asynchronous Pattern (EAP) 801
Background Worker Pattern 804
Establishing the Pattern 807
Exception Handling 808
Contents
Windows UI Programming 809
Windows Forms 809
Windows Presentation Foundation (WPF) 811
Summary 814

20 Platform Interoperability and Unsafe Code 
Platform Invoke 816
Declaring External Functions 817
Parameter Data Types 818
Using ref Rather Than Pointers 819
Using StructLayoutAttribute for Sequential Layout 820
Error Handling 821
Using SafeHandle 823
Calling External Functions 826
Simplifying API Calls with Wrappers 828
Function Pointers Map to Delegates 829
Guidelines 829
Pointers and Addresses 830
Unsafe Code 830
Pointer Declaration 832
Assigning a Pointer 834
Dereferencing a Pointer 837
Accessing the Member of a Referent Type 839
Summary 839

21 The Common Language Infrastructure 
Defining the Common Language Infrastructure (CLI) 844
CLI Implementations 845
C# Compilation to Machine Code 847
Runtime 849
Garbage Collection 849
Garbage Collection on .NET 850
Type Safety 851
Code Access Security 852
Platform Portability 852
Performance 853
Application Domains 854
Assemblies, Manifests, and Modules 855
Common Intermediate Language (CIL) 858
Common Type System (CTS) 858
Common Language Specification








Download Tutorial C# : Essential C# / PDF
















Tutorial C# : Essential C# / PDF




0 commentaires: