Look sharp-learn or refresh your C# skills with the latest version
C# is one of the most popular programming languages, and frequent updates help it keep pace as the world of coding changes. You can keep pace too, thanks to C# 10.0 All-in-One For Dummies, where you'll learn the basics of the language itself, how to code in Visual Studio, and how to take advantage of the new features in the latest release. At every stage of your career, you'll need to know the cutting-edge trends and techniques that clients want. This book has your back, with info on object-oriented programming, writing secure code, building web applications, and more.
The six standalone mini-books you'll find inside this all-in-one will take you through the changes to C# and the practical applications and dev tools that you need to know. New features covered include records, init only setters, top-level statements, pattern matching enhancements, fit and finish features, and a lot more. Plus, this version is packed with more examples and code snippets, so you can sharply see C# in action!
You need an easy-to-read C# guide that will help you understand the incoming updates, and this For Dummies reference is it.
John Paul Mueller is an author and technical editor with experience in application development, database management, machine learning, and deep learning. He has written hundreds of books and articles helping everyday people learn everything from networking to database management.
Introduction 1
About This Book 1
Foolish Assumptions 2
Icons Used in This Book 3
Beyond the Book 3
Where to Go from Here 4
Book 1: The Basics of C# Programming 5
Chapter 1: Creating Your First C# Console Application 7
Getting a Handle on Computer Languages, C#, and NET 8
What's a program? 8
What's C#? 9
What's NET? 9
What is Visual Studio 2022? 10
Creating Your First Console Application 11
Creating the source program 11
Taking it out for a test drive 17
Making Your Console App Do Something 17
Reviewing Your Console Application 18
The program framework 19
Comments 19
The meat of the program 19
Replacing All that Ceremonial Code: Top-Level Statements 20
Introducing the Toolbox Trick 21
Saving code in the Toolbox 22
Reusing code from the Toolbox 22
Interacting with C# Online 23
Working with Jupyter Notebook: The Short Version 23
Chapter 2: Living with Variability - Declaring Value-Type Variables 25
Declaring a Variable 26
What's an int? 27
Rules for declaring variables 28
Variations on a theme: Different types of int 28
Representing Fractions 30
Handling Floating-Point Variables 31
Declaring a floating-point variable 31
Examining some limitations of floating-point variables 32
Using the Decimal Type: Is It an Integer or a Float? 34
Declaring a decimal 35
Comparing decimals, integers, and floating-point types 35
Examining the bool Type: Is It Logical? 36
Checking Out Character Types 36
The char variable type 36
Special chars 37
The string type 37
What's a Value Type? 39
Comparing string and char 40
Calculating Leap Years: DateTime 41
Declaring Numeric Constants 43
Changing Types: The Cast 44
Letting the C# Compiler Infer Data Types 46
Chapter 3: Pulling Strings 49
The Union Is Indivisible, and So Are Strings 50
Performing Common Operations on a String 51
Comparing Strings 52
Equality for all strings: The Compare() method 52
Would you like your compares with or without case? 56
What If I Want to Switch Case? 56
Distinguishing between all-uppercase and all-lowercase strings 56
Converting a string to upper- or lowercase 57
Looping through a String 58
Searching Strings 59
Can I find it? 59
Is my string empty? 60
Using advanced pattern matching 60
Getting Input from Users in Console Applications 61
Trimming excess white space 62
Parsing numeric input 62
Handling a series of numbers 64
Joining an array of strings into one string 66
Controlling Output Manually 67
Using the Trim() and Pad() methods 67
Using the Concatenate() method 69
Go Ahead and Split() that concatenate program 71
Formatting Your Strings Precisely 72
Using the String.Format() method 72
Using the interpolation method 77
StringBuilder: Manipulating Strings More Efficiently 77
Chapter 4: Smooth Operators 81
Performing Arithmetic 81
Simple operators 82
Operating orders 82
The assignment operator 84
The increment operator 84
Performing Logical Comparisons - Is That Logical? 85
Comparing floating-point numbers: Is your float bigger than mine? 86
Compounding the confusion with compound logical operations 87
Matching Expression Types at TrackDownAMate.com 89
Calculating the type of an operation 89
Assigning types 91
Changing how an operator works: Operator overloading 92
Chapter 5: Getting into the Program Flow 95
Branching Out with if and switch 96
Introducing the if statement 97
Examining the else statement 100
Avoiding even the else 101
Nesting if statements 102
Running the switchboard 104
Here We Go Loop-the-Loop 110
Looping for a while 111
Doing the do while loop 114
Breaking up is easy to do 115
Looping until you get it right 116
Focusing on scope rules 120
Looping a Specified Number of Times with for 120
A for loop example 121
Why do you need another loop? 122
Nesting loops 123
Chapter 6: Lining Up Your Ducks with Collections 125
The C# Array 126
The argument for the array 126
The fixed-value array 127
The variable-length array 129
Initializing an array 132
Processing Arrays by Using foreach 133
Working with foreach loops in a standard way 133
Relying on GetEnumerator support 134
Sorting Arrays of Data 136
Using var for Arrays 139
Loosening Up with C# Collections 140
Understanding Collection Syntax 141
Figuring out 142
Going generic 142
Using Lists 143
Instantiating an empty list 143
Creating a list of type int 144
Converting between lists and arrays 144
Searching lists 144
Performing other list tasks 145
Using Dictionaries 145
Creating a dictionary 145
Searching a dictionary 146
Iterating a dictionary 146
Array and Collection Initializers 147
Initializing arrays 148
Initializing collections 148
Using Sets 149
Performing special set tasks 149
Creating a set 150
Adding items to a set 150
Performing a union 151
Performing an intersection 152
Performing a difference 153
Chapter 7: Stepping through Collections 155
Iterating through a Directory of Files 156
Using the LoopThroughFiles program 156
Getting started 157
Obtaining the initial input 157
Creating a list of files 159
Formatting the output lines 160
Displaying the hexadecimal output 161
Running from inside Visual Studio 163
Iterating foreach Collections: Iterators 164
Accessing a collection: The general problem 164
Letting C# access data foreach container 167
Accessing Collections the Array Way: Indexers 169
Indexer format 169
An indexer program example 170
Looping Around the Iterator Block 173
Creating the required iterator block framework 174
Iterating days of the month: A first example 176
What a collection is, really 177
Iterator syntax gives up so easily 178
Iterator blocks of all shapes and sizes 180
Chapter 8: Buying Generic 187
Writing a New Prescription: Generics 188
Generics are type-safe 188
Generics are efficient 189
Classy Generics: Writing Your Own 190
Shipping packages at OOPs 190
Queuing at OOPs: PriorityQueue 191
Unwrapping the package 194
Touring Main() 196
Writing generic code the easy way 197
Saving PriorityQueue for last 198
Using a (nongeneric) Simple Factory class 201
Understanding Variance in Generics 205
Contravariance 206
Covariance 208
Chapter 9: Some Exceptional Exceptions 209
Using an Exceptional Error-Reporting Mechanism 210
About try blocks 211
About catch blocks 211
About finally blocks 212
What happens when an exception is thrown 213
Throwing Exceptions Yourself 215
Can I Get an Exceptional Example? 216
Working with Custom Exceptions 220
Planning Your Exception-Handling Strategy 221
Some questions to guide your planning 221
Guidelines for code that handles errors well 222
How to find out which methods throw which exceptions 223
Grabbing Your Last Chance to Catch an Exception 225
Throwing Expressions 226
Chapter 10: Creating Lists of Items with Enumerations 229
Seeing Enumerations in the Real World 230
Working with Enumerations 231
Using the enum keyword 231
Creating enumerations with initializers 233
Specifying an enumeration data type 234
Creating Enumerated Flags 235
Defining Enumerated Switches 237
Working with Enumeration Methods 238
Book 2: Object-Oriented C# Programming 241
Chapter 1: Showing Some Class 243
A Quick Overview of Object-Oriented Programming 244
Considering OOP basics 244
Extending classes to meet other needs 244
Keeping objects safe 245
Working with objects 246
Defining a Class and an Object 246
Defining a class 247
What's the object? 249
Accessing the Members of an Object 250
Working with Object-Based Code 250
Using the traditional approach 250
Using the C# 9.0 approach 252
Discriminating between Objects 253
Can You Give Me References? 254
Classes That Contain Classes Are the Happiest Classes in the World 256
Generating Static in Class Members 257
Defining const and readonly Data Members 259
Chapter 2: We Have Our Methods 261
Defining and Using a Method 262
Method Examples for Your Files 263
Understanding the problem 264
Working with standard coding methods 265
Applying a refactoring approach 268
Working with local functions 271
Having Arguments with Methods 273
Passing an argument to a method 273
Passing multiple arguments to methods 274
Matching argument definitions with usage 276
Overloading a method doesn't mean giving it too much to do 276
Implementing default arguments 278
Using the Call-by-Reference Feature 280
Defining a Method with No Return Value 281
Returning Multiple Values Using Tuples 282
Using a tuple 283
Relying on the Create() method 284
Creating tuples with more than two items 284
Chapter 3: Let Me Say This about this 287
Passing an Object to a Method 288
Comparing Static and Instance Methods 290
Employing static properties and methods effectively 291
Employing instance properties and methods effectively 293
Expanding a method's full name 295
Accessing the Current Object 296
What is the this keyword? 298
When is the this keyword explicit? 299
Using Local Functions 300
Creating a basic local function 300
Using attributes with local functions 301
Chapter 4: Holding a Class Responsible 303
Restricting Access to Class Members 303
A public example of public BankAccount 304
Jumping ahead - other levels of security 306
Why You Should Worry about Access Control 307
Accessor methods 308
Working with init-only setters 309
Access control to the rescue - an example 311
Defining Class Properties 313
Static properties 315
Properties with side effects 315
Accessors with access levels 316
Using Target Typing for Your Convenience 316
Dealing with Covariant Return Types 319
Getting Your Objects Off to a Good Start - Constructors 320
The C#-Provided Constructor 321
Replacing the Default Constructor 322
Constructing something 324
Initializing an object directly with an initializer 326
Seeing that construction stuff with initializers 326
Initializing an object without a constructor 327
Using Expression-Bodied Members 329
Creating expression-bodied methods 329
Defining expression-bodied properties 329
Defining expression-bodied constructors and destructors 330
Defining expression-bodied property accessors 330
Defining expression-bodied event accessors 331
Chapter 5: Inheritance: Is That All I Get? 333
Why You Need Inheritance 334
Inheriting from a BankAccount Class (a More Complex Example) 335
Working with the basic update 336
Tracking the BankAccount and SavingsAccount classes features 339
IS_A versus HAS_A - I'm So Confused_A 342
The IS_A relationship 342
Gaining access to BankAccount by using containment 343
The HAS_A relationship 345
When to IS_A and When to HAS_A 346
Other Features That Support Inheritance 346
Substitutable classes 346
Invalid casts at runtime 347
Avoiding invalid conversions with the is operator 348
Avoiding invalid conversions with the as operator 349
Chapter 6: Poly-what-ism? 353
Overloading an Inherited Method 354
It's a simple case of method overloading 354
Different class, different method 355
Peek-a-boo - hiding a base class method 355
Polymorphism 361
Using the declared type every time (Is that so wrong?) 362
Using is to access a hidden method polymorphically 364
Declaring a method virtual and overriding it 365
Getting the most benefit from polymorphism 368
C# During Its Abstract Period 368
Class factoring 369
The abstract class: Left with nothing but a concept 373
How do you use an abstract class? 374
Creating an abstract object - not! 377
Sealing a Class 377
Chapter 7: Interfacing with the Interface 379
Introducing CAN_BE_USED_AS 379
Knowing What an Interface Is 381
How to implement an interface 382
Using the newer C# 8.0 additions 383
How to name your interface 386
Why C# includes interfaces 386
Mixing inheritance and interface implementation 387
And he-e-e-re's the payoff 387
Using an Interface 388
As a method return type 389
As the base type of an array or collection 389
As a more general type of object reference 390
Using the C# Predefined Interface Types 390
Looking at a Program That CAN_BE_USED_AS an Example 391
Creating your own interface at home in your spare time 391
Implementing the incomparable I Comparable interface 392
Creating a list of students 394
Testing everything using Main() 395
Unifying Class Hierarchies 396
Hiding Behind an Interface 399
Inheriting an Interface 401
Using Interfaces to Manage Change in Object-Oriented Programs 402
Making flexible dependencies through interfaces 403
Abstract or concrete: When to use an abstract class and when to use an interface 404
Doing HAS_A with interfaces 405
Chapter 8: Delegating Those Important Events 407
E.T., Phone Home - The Callback Problem 408
Defining a Delegate 408
Pass Me the Code, Please - Examples 411
Delegating the task 411
First, a simple example 412
Considering the Action, Func, and Predicate delegate types 413
A More Real-World Example 415
Putting the app together 416
Setting the properties and adding event handlers 418
Looking at the workhorse code 419
Shh! Keep It Quiet - Anonymous Methods 421
Defining the basic anonymous method 421
Using static anonymous methods 422
Working with lambda discard parameters 424
Stuff Happens - C# Events 424
The Observer design pattern 425
What's an event? Publish/Subscribe 425
How a publisher advertises its events 426
How subscribers subscribe to an event 427
How to publish an event 427
How to pass extra information to an event handler 428
A recommended way to raise your events 429
How observers "handle" an event 430
Chapter 9: Can I Use Your Namespace in the Library? 433
Dividing a Single Program into Multiple Source Files 434
Working with Global using Statements 435
Dividing a Single Program into Multiple Assemblies 437
Executable or library? 437
Assemblies 437
Executables 438
Class libraries 439
Putting Your Classes into Class Libraries 439
Creating the projects for a class library 439
Creating a stand-alone class library 440
Adding a second project to an existing solution 442
Creating the code for the library 445
Using a test application to test a library 446
Going Beyond Public and Private: More Access Keywords 448
Internal: For CIA eyes only 448
Protected: Sharing with subclasses 451
Putting Classes into Namespaces 453
Declaring a namespace 454
Using file-scoped namespaces 456
Relating namespaces to the access keyword story 456
Using fully qualified names 458
Working with partial classes 459
Working with Partial Methods 463
Defining what partial methods do 463
Creating a partial method 464
Chapter 10: Improving Productivity with Named and Optional Parameters 465
Exploring Optional Parameters 466
Working with optional value parameters 466
Avoiding optional reference types 468
Looking at Named Parameters 470
Using Alternative Methods to Return Values 470
Output (out) parameters 471
Working with out variables 471
Returning values by reference 472
Dealing with null Parameters 473
Chapter 11: Interacting with Structures 475
Comparing Structures to Classes 476
Considering struct limits 476
Understanding the value type difference 477
Determining when to use struct versus class 477
Creating Structures 478
Defining a basic struct 478
Including common struct elements 479
Using supplemental struct elements 482
Working with Read-only Structures 485
Working with Reference Structures 487
Using Structures as Records 489
Managing a single record 489
Adding structures to arrays 489
Overriding methods 490
Using the New Record Type 491
Comparing records to structures and classes 491
Working with a record 492
Using the positional syntax for property definition 493
Understanding value equality 494
Creating safe changes: Nondestructive mutation 494
Using the field keyword 495
Book 3: Designing For C# 497
Chapter 1: Writing Secure Code 499
Designing Secure Software 500
Determining what to protect 500
Documenting the components of the program 501
Decomposing components into functions 502
Identifying potential threats in functions 502
Building Secure Windows Applications 503
Authentication using Windows logon 503
Encrypting information 507
Deployment security 507
Using System.Security 508
Chapter 2: Accessing Data 509
Getting to Know System.Data 510
How the Data Classes Fit into the Framework 512
Getting to Your Data 512
Using the System.Data Namespace 513
Setting up a sample database schema 513
Creating the data access project 514
Connecting to a data source 514
Working with the visual tools 519
Writing data code 521
Chapter 3: Fishing the File Stream 525
Going Where the Fish Are: The File Stream 525
Streams 526
Readers and writers 527
StreamWriting for Old Walter 528
Using the stream: An example 529
Using some better fishing gear: The using statement 534
Pulling Them Out of the Stream: Using StreamReader 537
More Readers and Writers 539
Exploring More Streams than Lewis and Clark 541
Chapter 4: Accessing the Internet 543
Getting to Know System.Net 544
How Net Classes Fit into the Framework 545
Understanding the System.Net subordinate namespaces 545
Working with the System.Net classes 548
Using the System.Net Namespace 549
Checking the network status 549
Downloading a file from the Internet 551
Emailing a status report 553
Logging network activity 556
Chapter 5: Creating Images 559
Getting to Know System.Drawing 560
Graphics 561
Pens 562
Brushes 563
Text 563
How the Drawing Classes Fit into the Framework 564
Using the System.Drawing Namespace 565
Getting started 565
Setting up the project 567
Handling the score 567
Creating an event connection 569
Drawing the board 570
Printing the score 572
Starting a new game 574
Chapter 6: Programming Dynamically! 575
Shifting C# Toward Dynamic Typing 576
Employing Dynamic Programming Techniques 578
Putting Dynamic to Use 580
Classic examples 580
Making static operations dynamic 581
Understanding what's happening under the covers 581
Running with the Dynamic Language Runtime 582
Using Static Anonymous Functions 585
Book 4: A Tour of Visual Studio 587
Chapter 1: Getting Started with Visual Studio 589
Versioning the Versions 590
An overview of Visual Studio 2022 updates 590
Community edition 592
Professional edition 594
Enterprise edition 594
MSDN 595
Installing Visual Studio 596
Breaking Down the Projects 597
Exploring the Create a New Project dialog box 600
Understanding solutions and projects 601
Chapter 2: Using the Interface 603
Designing in the Designer 604
Universal Windows Platform (UWP) application 604
Windows Presentation Foundation (WPF) 607
Windows Forms 609
Data View 609
Paneling the Studio 610
Solution Explorer 610
Properties 613
The Toolbox 614
Server Explorer 615
Class View 617
Coding in the Code Editor 618
Exercising the Code Editor 618
Exploring the auxiliary windows 619
Using the Tools of the Trade 621
The Tools menu 622
Building 623
Using the Debugger as an Aid to Learning 623
Stepping through code 623
Going to a particular code location 624
Watching application data 625
Viewing application internals 626
Chapter 3: Customizing Visual Studio 627
Setting Options 628
Environment 629
Language 630
Neat stuff 631
Creating Your Own Templates 632
Developing a project template 632
Developing an item template 635
Book 5: Windows Development with Wpf 639
Chapter 1: Introducing WPF 641
Understanding What WPF Can Do 642
Introducing XAML 643
Diving In! Creating Your First WPF Application 644
Declaring an application-scoped resource 647
Making the application do something 648
Whatever XAML Can Do, C# Can Do Better! 650
Chapter 2: Understanding the Basics of WPF 653
Using WPF to Lay Out Your Application 654
Arranging Elements with Layout Panels 655
The Stack panel 656
The Wrap panel 660
The Dock panel 661
Canvas 662
The Grid 662
Putting it all together with a simple data entry form 669
Exploring Common XAML Controls 672
Display-only controls 672
Basic input controls 674
List-based controls 677
Chapter 3: Data Binding in WPF 681
Getting to Know Dependency Properties 682
Exploring the Binding Modes 683
Investigating the Binding Object 683
Defining a binding with XAML 684
Defining a binding with C# 686
Editing, Validating, Converting, and Visualizing Your Data 687
Validating data 693
Converting your data 697
Finding Out More about WPF Data Binding 705
Chapter 4: Practical WPF 707
Commanding Attention 708
Traditional event handling 708
ICommand 709
Routed commands 710
Using Built-In Commands 711
Using Custom Commands 713
Defining the interface 713
Creating the window binding 714
Ensuring that the command can execute 714
Performing the task 715
Using Routed Commands 717
Defining the Command class 717
Making the namespace accessible 718
Adding the command bindings 718
Developing a user interface 718
Developing the custom command code-behind 719
Chapter 5: Programming for Windows 10 and Above 721
What is the Universal Windows Platform (UWP)? 722
Devices Supported by the UWP 725
Creating Your Own UWP App 726
Configuring Developer Mode 726
Defining the project 732
Creating an interface 734
Adding some background code 738
Choosing a test device 739
Working with NET Core Applications 740
Book 6: Web Development with Asp.Net 743
Chapter 1: Creating a Basic ASP.NET Core App 745
Understanding the ASP.NET Core Templates 746
Starting with nothing using ASP.NET Core Empty 746
Creating a basic app using the ASP.NET Core Web App 748
Fumbling around with HTTPS-enabled sites 749
Building in business logic using ASP.NET Core App (Model-View-Controller) 751
Developing a programming interface using ASP.NET
Core Web API 752
An overview of those other weird templates 753
Developing a Basic Web App 754
Creating the project 754
Considering the development process 756
Adding web content 757
Making some basic changes to the first page 759
Chapter 2: Employing the Razor Markup Language 761
Avoiding Nicks from Razor 762
Comparing Razor to its predecessors 762
Considering the actual file layout 763
Understanding the syntax rules for C# 766
Working with some Razor basics 767
Creating Variables 770
Keeping Things Logical 771
Starting simply by using if 771
Sleeping at the switch 771
Implementing Loops 772
Creating an array 772
Performing tasks a specific number of times using for 773
Processing an unknown number of times using for each and while 773
Chapter 3: Generating and Consuming Data 775
Understanding Why These Projects Are Important 776
Serialized Data Isn't for Breakfast 777
Developing a Data Generator and API 778
Creating the WeatherForecast project 778
Making the data believable 781
Looking at the API configuration 783
Checking the API for functionality 784
Creating a Consumer Website 786
Creating the RetrieveWeatherForecast project 786
Developing a user interface 787
Getting and deserializing the data 789
Seeing the application in action 793
Index 795