byjohn sempf, andchuck
TRANSCRIPT
byJohn Paul Mueller,Bill Sempf, and Chuck Sphar
dummiesAWiley Brand
]fj|?|eg|G^INTRODUCTION 1
About This Book 1
Foolish Assumptions 2
Icons Used in This Book 2
Beyond the Book 3
Where to Go from Here 4
BOOK 1: THE BASICS OF C# PROGRAMMING 5
chapter v. Creating Your First C# Console Application i
Getting a Handle on Computer Languages, C#, and .NET 7
What's a program? 8
What's C#? 8
What's .NET? 9
What is Visual Studio 2017? What about Visual C#? 10
Creating Your First Console Application 11
Creating the source program 11
Taking it out for a test drive 16
Making Your Console App Do Something 17
Reviewing Your Console Application 18
The program framework 18
Comments 19
The meat of the program 20
Introducing the Toolbox Trick 21
Saving code in the Toolbox 21
Reusing code from the Toolbox 22
chapter 2: Living with Variability — DeclaringValue-Type Variables 23
Declaring a Variable 24
What's an int? 25
Rules for declaring variables 25
Variations on a theme: Different types of int 26
Representing Fractions 27
Handling Floating-Point Variables 28
Declaring a floating-point variable 29
Examining some limitations of floating-point variables 30
Using the Decimal Type: Is It an Integer or a Float? 31
Declaring a decimal 32
Comparing decimals, integers, and floating-point types 32
Table of Contents vii
Examining the bool Type: Is It Logical? 33
Checking Out Character Types 33
The char variable type •34
Special chars 34
The string type 35
What's a Value Type? 36
Comparing string and char 37
Calculating Leap Years: DateTime. 38
Declaring Numeric Constants 40
Changing Types: The Cast 41
Letting the C# Compiler Infer Data Types 42
chapter 3: Pulling Strings 45
The Union Is Indivisible, and So Are Strings 46
Performing Common Operations on a String 48
Comparing Strings 48
Equality for all strings: The CompareO method 49
Would you like your compares with or without case? 52
What If I Want to Switch Case? 53
Distinguishing between all-uppercase andall-lowercase strings 53
Converting a string to upper- or lowercase 54
Looping through a String 54
Searching Strings 55
Can I find it? 55
Is my string empty? —56
Getting Input from the Command Line 57
Trimming excess white space 57
Parsing numeric input 57
Handling a series of numbers 60
Joining an array of strings into one string 62
Controlling Output Manually 62
Using the Trim() and Pad() methods 63
Using the Concatenate!) method 65
Let's Split() that concatenate program 67
Formatting Your Strings Precisely 68
StringBuilder: Manipulating Strings More Efficiently 73
chapter4: Smooth Operators 75
Performing Arithmetic 75
Simple operators 75
Operating orders 76
The assignment operator 77
The increment operator 78
viii C# 7.0 All-in-One For Dummies
Performing Logical Comparisons — Is That Logical? 79
Comparing floating-point numbers: Is your float
bigger than mine? 80
Compounding the confusion with compoundlogical operations 81
Matching Expression Types atTrackDownAMate.com 83
Calculating the type of an operation 84
Assigning types 85
Changing how an operator works: Operator overloading 86
chapters: Getting into the Program Flow 89
Branching Out with if and switch 90
Introducing the if statement 91
Examining the else statement 94
Avoiding even the else 95
Nesting if statements 96
Running the switchboard 99
Here We Go Loop-the-Loop 101
Looping for a while 102
Doing the do...
while loop 106
Breaking up is easy to do 106
Looping until you get it right 107
Focusing on scope rules 112
Looping a Specified Number of Times with for 112
An example 113
Why do you need another loop? 114
Nesting Loops 115
Don't goto Pieces 116
chapter 6: Lining Up Your Ducks with Collections 119
The C# Array 120
The argument for the array 120
The fixed-value array 121
The variable-length array 122
The Length property 125
Initializing an array 126
Processing Arrays by Using foreach 126
Sorting Arrays of Data 128
Using var for Arrays 132
Loosening Up with C# Collections 133
Understanding Collection Syntax 134
Figuring out <T> 135
Going generic 135
Table ofContents ix
Using Lists, 136
Instantiating an empty list 136
Creating a list of type int 137
Creating a list to hold objects 137
Converting between lists and arrays 138
Counting list elements 138
Searching lists 138
Performing other list tasks ...138
Using Dictionaries 139
Creating a dictionary 139
Searching a dictionary 139
Iterating a dictionary 140
Array and Collection Initializers 141
Initializing arrays141
Initializing collections 141
Using Sets 142
Performing special set tasks 143
Creating a set 143
Adding items to a set 144
Performing a union 144
Performing an intersection 145
Performing a difference 147
On Not Using Old-Fashioned Collections 147
chapter 7: Stepping through Collections 149
Iterating through a Directory of Files .149
Using the LoopThroughFiles program 150
Getting started 151
Obtaining the initial input 151
Creating a list of files 153
Formating the output lines 154
Displaying the hexadecimal output 155
Iterating foreach Collections: Iterators* 157
Accessing a collection: The general problem 157
Letting C# access data foreach container 159
Accessing Collections the Array Way: Indexers 160
Indexer format 161
An indexer program example 161
Looping Around the Iterator Block 165
Creating the required iterator block framework 166
Iterating days of the month: A first example 168
What a collection is, really 170
Iterator syntax gives up so easily 171
Iterator blocks of all shapes and sizes 173
X C# 7,0 All-in-One For Dummies
chapter s: Buying Generic m
Writing a New Prescription: Generics 178
Generics are type-safe 178
Generics are efficient 179
Classy Generics: Writing Your Own 179
Shipping packages at OOPs 180
Queuing at OOPs: PriorityQueue 181
Unwrapping the package 186
Touring Main() 188
Writing generic code the easy way 189
Saving PriorityQueue for last 190
Using a (nongeneric) Simple Factory class 193
Tending to unfinished business 195
Revising Generics 197
Variance 198
Contravariance 199
Covariance 200
chapter9: Some Exceptional Exceptions 201
Using an Exceptional Error-Reporting Mechanism 202
About try blocks 203
About catch blocks 203
About finally blocks 204
What happens when an exception is thrown 205
Throwing Exceptions Yourself 207
Knowing What Exceptions Are For 207
Can I Get an Exceptional Example? 208
Knowing what makes the example exceptional 210
Tracing the stack 210
Assigning Multiple catch Blocks 211
Planning Your Exception-Handling Strategy 214
Some questions to guide your planning 214
Guidelines for code that handles errors well 215
How to analyze a method for possible exceptions 216
How to find out which methods throw which exceptions 218
Grabbing Your Last Chance to Catch an Exception 219
Throwing Expressions 220
chapter 10: Creating Lists of Items with Enumerations 223
Seeing Enumerations in the Real World 224
Working with Enumerations 225
Using the enum keyword 225
Creating enumerations with initializers 226
Specifying an enumeration data type 227
Creating Enumerated Flags 228
Defining Enumerated Switches 230
Table of Contents xi
BOOK 2: OBJECT-ORIENTED C# PROGRAMMING 233
chapter 1: Object-Oriented Programming —What's It All About? 235
Object-Oriented Concept #1: Abstraction 235
Preparing procedural trips 236
Preparing object-oriented trips 237
Object-Oriented Concept #2: Classification 238
Why Classify? 238
Object-Oriented Concept #3: Usable Interfaces 239
Object-Oriented Concept #4: Access Control 240
How C# Supports Object-Oriented Concepts 241
chapter 2: Showing Some Class 243
Defining a Class and an Object 244
Defining a class 244
What's the object? 245
Accessing the Members of an Object 246
An Object-Based Program Example .247
Discriminating between Objects 249
Can You Give Me References? 249
Classes That Contain Classes Are the Happiest Classesin the World 252
Generating Static in Class Members 253
Defining const and readonly Data Members 255
chapters: We Have Our Methods 257
Defining and Using a Method 257
A Method Example for Your Files 259
Having Arguments with Methods 267
Passing an argument to a method 267
Passing multiple arguments to methods 268
Matching argument definitions with usage 270
Overloading a method doesn't mean giving it toomuch to do 271
Implementing default arguments 272
Returning Values after Christmas 275
Returning a value via return postage 276
Defining a method with no value 277
Returning Multiple Values Using Tuples 279
Using a single-entry tuple 279
Relying on the Create() method 280
Using a multi-entry tuple 281
Creating tuples with more than two items 282
Xii C# 7,0 All-in-One For Dummies
chapter 4: Let Me Say This about this 283
Passing an Object to a Method 283
Defining Methods 285
Defining a static method 286
Defining an instance method 287
Expanding a method's full name 289
Accessing the Current Object 290
What is the this keyword? 292
When is this explicit? 293
What happens when you don't have this? 296
Using Local Functions 298
chapters: Holding a Class Responsible 301
Restricting Access to Class Members 301
A public example of public BankAccount 302
Jumping ahead — other levels of security 305
Why You Should Worry about Access Control 306
Accessor methods 307
Access control to the rescue — an example 307
So what? 311
Defining Class Properties 312
Static properties 313
Properties with side effects 314
Letting the compiler write properties for you 314
Accessors with access levels 315
Getting Your Objects Off to a Good Start — Constructors 315
The C#-Provided Constructor 316
Replacing the Default Constructor 317
Constructing something 319
Initializing an object directly with an initializer 321
Seeing that construction stuff with initializers 322
Initializing an object without a constructor 323
Using Expression-Bodied Members 324
Creating expression-bodied methods 325
Defining expression-bodied properties 325
Defining expression-bodied constructors and destructors 325
Defining expression-bodied property accessors 326
Defining expression-bodied event accessors 326
chapter 6: Inheritance: Is That All I Get? 329
Class Inheritance 330
Why You Need Inheritance 332
Inheriting from a BankAccount Class (a More Complex Example)... 333
Table of Contents xiii
IS_A versus HAS_A— I'm So Confused_A 336
The IS_A relationship 337
Gaining access to BankAccount by using containment 338
The HAS_A relationship 339
When to IS_A and When to HAS_A 340
Other Features That Support Inheritance 340
Substitutable classes 341
Invalid casts at runtime 341
Avoiding invalid conversions with the is operator 342
Avoiding invalid conversions with the as operator 343
The object Class 344
Inheritance and the Constructor 345
Invoking the default base class constructor 346
Passing arguments to the base class constructor 347
Getting specific with base 349
The Updated BankAccount Class 350
CHAPTER 7: Poty-What-ISm? 357
Overloading an Inherited Method 358
It's a simple case of method overloading 358
Different class, different method 359
Peek-a-boo — hiding a base class method 359
Calling back to base 364
Polymorphism 366
Using the declared type every time (Is that so wrong?) 368
Using is to access a hidden method polymorphically 369
Declaring a method virtual and overriding it 371
Getting the most benefit from polymorphism 374
The Class Business Card: ToStringO 374
C# During Its Abstract Period 374
Class factoring ..375
The abstract class: Left with nothing but a concept. 380
How do you use an abstract class? 381
Creating an abstract object — not! 383
Sealing a Class 383
chapters: Interfacing with the Interface 385
Introducing CAN_BE_USED_AS 385
Knowing What an Interface Is 387
How to implement an interface. 388
How to name your interface 389
Why C# includes interfaces 389
Mixing inheritance and interface implementation 389
And he-e-e-re's the payoff 390
Xiv C# 7.0 AIMn-One For Dummies
Using an Interface 391
As a method return type 391
As the base type of an array or collection 391
As a more general type of object reference 392
Using the C# Predefined Interface Types 392
Looking at a Program That CAN_BE_USED_AS an Example 393
Creating your own interface at home in your spare time 393
Implementing the incomparable IComparable<T> interface 395
Putting it all together 396
Getting back to the Main() event 400
Unifying Class Hierarchies 401
Hiding Behind an Interface 403
Inheriting an Interface 406
Using Interfaces to Manage Change in Object-OrientedPrograms 407
Making flexible dependencies through interfaces 408
Abstract or concrete: When to use an abstract class
and when to use an interface 408
Doing HAS_A with interfaces 409
chapter 9: Delegating Those Important Events 411
E.T., Phone Home — The Callback Problem 412
Defining a Delegate 412
Pass Me the Code, Please — Examples 414
Delegating the task 415
First, a simple example 415
A More Real-World Example 417
Getting an overview of the bigger example 417
Putting the app together 418
Looking at the code 421
Tracking the delegate life cycle 423
Shh! Keep It Quiet —Anonymous Methods 426
Stuff Happens — C# Events 427
The Observer design pattern 427
What's an event? Publish/Subscribe 427
How a publisher advertises its events 428
How subscribers subscribe to an event 429
How to publish an event 429
How to pass extra information to an event handler 430
A recommended way to raise your events 431
How observers "handle" an event 432
Table of Contents XV
chapter 10: Can I Use Your Namespace in the Library? 435
Dividing a Single Program into Multiple Source Files 436
Dividing a Single Program into Multiple Assemblies 437
Executable or library? 437
Assemblies 438
Executables 439
Class libraries 439
Putting Your Classes into Class Libraries 440
Creating the projects for a class library 440
Creating a stand-alone class library 440
Adding a second project to an existing solution 442
Creating classes for the library 443
Using a test application to test a library 444
Going Beyond Public and Private: More Access Keywords 446
Internal: For CIA eyes only 446
Protected: Sharing with subclasses 449
Protected internal: Being a more generous protector 451
Putting Classes into Namespaces 452
Declaring a namespace 453
Relating namespaces to the access keyword story 455
Using fully qualified names 456
chapter ii: Improving Productivity with Namedand Optional Parameters. 459
Exploring Optional Parameters 460
Reference types 462
Output parameters 464
Looking at Named Parameters 464
Dealing with Overload Resolution 465
Using Alternative Methods to Return Values 466
Working with out variables 466
Returning values by reference 467
chapter 12: Interacting with Structures 469
Comparing Structures to Classes 470
Considering struct limits 470
Understanding the value type difference 470
Determining when to use struct versus class 471
Creating Structures 472
Defining a basic struct 472
Including common struct elements 473
Using Structures as Records 479
Managing a single record 479
Adding structures to arrays 480
Overriding methods 481
XVI C# 7.0 All-in-One For Dummies
BOOK 3: DESIGNING FOR C# 483
chapter 1: Writing Secure Code ....485
Designing Secure Software 486
Determining what to protect 486
Documenting the components of the program 486
Decomposing components into functions 487
Identifying potential threats in functions 487
Rating the risk 488
Building Secure Windows Applications 488
Authentication using Windows login 489
Encrypting information 492
Deployment security 493
Building Secure Web Forms Applications 493
SQL Injection attacks 494
Script exploits 495
Best practices for securing Web Forms applications 497
Using System.Security 498
chapter 2: Accessing Data 499
Getting to Know System.Data 500
How the Data Classes Fit into the Framework 502
Getting to Your Data 502
Using the System.Data Namespace 503
Setting up a sample database schema 503
Connecting to a data source 504
Working with the visual tools 510
Writing data code 513
Using the Entity Framework 516
chapters: Fishing the File Stream 521
Going Where the Fish Are: The File Stream 521
Streams 522
Readers and writers 522
StreamWriting for Old Walter 524
Using the stream: An example 525
Revving up a new outboard StreamWriter 528
Finally, you're writing! 531
Using some better fishing gear: The using statement 532
Pulling Them Out of the Stream: Using StreamReader 536
More Readers and Writers 540
Exploring More Streams than Lewis and Clark 542
Table of Contents xvii
chapter4: Accessing the Internet 543
Getting to Know System.Net 544
How Net Classes Fit into the Framework 545
Using the System.Net Namespace 547
Checking the network status 547
Downloading a file from the Internet 549
Emailing a status report 552
Logging network activity 555
chapter 5: Creating I mages 559
Getting to Know System.Drawing 560
Graphics 560
Pens 561
Brushes 561
Text 561
How the Drawing Classes Fit into the Framework 563
Using the System.Drawing Namespace 564
Getting started 564
Setting up the project 565
Handling the score '. 566
Creating an event connection 567
Drawing the board 568
Starting a new game 570
chapter6: Programming Dynamically! .571
Shifting C# Toward Dynamic Typing 572
Employing Dynamic Programming Techniques 574
Putting Dynamic to Use 576
Classic examples 577
Making static operations dynamic 577
Understanding what's happening under the covers 578
Running with the Dynamic Language Runtime 579
Dynamic Ruby 580
Dynamic C# 581
BOOK 4: A TOUR OF VISUAL STUDIO 583
chapter 1: Getting Started with Visual Studio 585
Versioning the Versions 586
Community edition 586
Professional edition .588
Enterprise edition 589
MSDN 590
XViii C# 7.0 All-in-One For Dummies
Installing Visual Studio 590
Breaking Down the Projects. 592
Exploring the New Project dialog box 593
Understanding solutions and projects 594
chapter2: Using the Interface 597
Designing in the Designer 597
Windows Presentation Foundation (WPF) 598
Windows Forms 600
Web Forms 601
Class Designer 602
Paneling the Studio 605
Solution Explorer 605
Properties 608
The Toolbox 609
Server Explorer 610
Class View 612
Coding in the Code Editor 612
Exercising the Code Editor 613
Exploring the auxiliary windows 614
Using the Tools of the Trade 616
The Tools menu 616
Building 618
Using the Debugger as an Aid to Learning 618
Stepping through code 618
Going to a particular code location 619
Watching application data 620
Viewing application internals 621
chapters: Customizing Visual Studio 623
Setting Options 624
Environment 625
Language 626
Neat stuff 627
Using Snippets 628
Using snippets 628
Using surround snippets 630
Making snippets 631
Deploying snippets •632
Sharing snippets 633
Hacking the Project Types 634
Hacking project templates 634
Hacking item templates 638
Table of Contents xix
BOOK 5: WINDOWS DEVELOPMENT WITH WPF 641
chapter 1: Introducing WPF 643
Understanding What WPF Can Do 643
Introducing XAML 645
Diving In! Creating Your First WPF Application 646
Declaring an application-scoped resource 648
Making the application do something 649
Whatever XAML Can Do, C# Can Do Better! 651
chapter 2: Understanding the Basics ofWPF 653
Using WPF to Lay Out Your Application 654
Arranging Elements with Layout Panels 655
The Stack Panel 655
The Wrap Panel 657
The Dock Panel 658
Canvas 659
The Uniform Grid 660
The Grid 661
Putting it all together with a simple data entry form 668
Panels of honorable mention 670
Exploring Common XAML Controls 671
Display-only controls 671
Basic input controls 673
List-based controls 676
chapters: Data Binding in WPF 681
Getting to Know Dependency Properties 681
Exploring the Binding Modes 682
Investigating the Binding Object 683
Defining a binding with XAML 683
Defining a binding with C# 686
Editing, Validating, Converting, and Visualizing Your Data 687
Validating data 692
Converting your data 696
Finding Out More about WPF Data Binding 704
chapter4: Practical WPF 705
Commanding Attention 705
Traditional event handling 706
ICommand 707
Routed commands 708
Using Built-in Commands 708
XX C# 7.0 All-in-One For Dummies
Using Custom Commands 711
Defining the interface 711
Creating the window binding 712
Ensuring that the command can execute 713
Performing the task 714
Using Routed Commands 716
Defining the Command class 716
Making the namespace accessible 716
Adding the command bindings 717
Developing a user interface 717
Developing the custom command code behind 718
BOOK 6: WEB DEVELOPMENT WITH ASP.NET 721
chapter 1= Looking at How ASP.NET Works with C# 723
Breaking Down Web Applications 724
Questioning the Client 726
Scripting the client 727
Getting information back from the client 728
Understanding the weaknesses of the browser 728
Dealing with Web Servers 730
Getting a PostBack (Hint: It's not a returned package) 731
It's a matter of state 734
chapter 2: BuildingWeb Applications 735
Working in Visual Studio 736
Two project approaches 736
Creating a standard project 737
Creating a website 748
Developing with Style 749
Coding behind 750
Building in n-tier 751
Modeling the View Controller 752
chapters: Controlling Your Development Experience 753
Showing Stuff to the User 754
Labels versus plain old text 754
Images 757
Panels and multiviews 758
Tables 759
Getting Some Input from the User 760
Using text input controls 760
Using single-item selection controls 762
Using multiple-item selection controls 764
Using other kinds of input controls 766
Submitting input with submit buttons 766
Table of Contents xxi
Data Binding 767
Setting up your markup for binding 767
Data binding using the code-behind 771
Using commonly bound controls 773
Styling Your Controls 775
Setting control properties 775
Binding styles with CSS 776
Making Sure the Site Is Accessible 777
Constructing User Controls 779
Making a new phone number User Control 779
Using your new control 780
chapter4: Leveraging the .NET Framework 783
Surfing Web Streams 784
Intercepting the request 784
Altering content sent to clients 788
SecuringASP.NET 789
Changing trusts 790
Fixing problems 790
Managing Files 791
Baking Cookies 792
Coding for client-side storage 793
How ASP.NET manages cookies for you 795
Tracing with TraceContext 796
Navigating with Site Maps 798
Navigating a site with SiteMap 800
INDEX 801
XXii C# 7.0 All-in-One For Dummies