32,99 €
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.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 1136
Veröffentlichungsjahr: 2022
C# 10.0 All-in-One For Dummies®
Published by: John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030-5774, www.wiley.com
Copyright © 2022 by John Wiley & Sons, Inc., Hoboken, New Jersey
Published simultaneously in Canada
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without the prior written permission of the Publisher. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions.
Trademarks: Wiley, For Dummies, the Dummies Man logo, Dummies.com, Making Everything Easier, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and may not be used without written permission. All other trademarks are the property of their respective owners. John Wiley & Sons, Inc. is not associated with any product or vendor mentioned in this book.
LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: WHILE THE PUBLISHER AND AUTHORS HAVE USED THEIR BEST EFFORTS IN PREPARING THIS WORK, THEY MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES REPRESENTATIVES, WRITTEN SALES MATERIALS OR PROMOTIONAL STATEMENTS FOR THIS WORK. THE FACT THAT AN ORGANIZATION, WEBSITE, OR PRODUCT IS REFERRED TO IN THIS WORK AS A CITATION AND/OR POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE PUBLISHER AND AUTHORS ENDORSE THE INFORMATION OR SERVICES THE ORGANIZATION, WEBSITE, OR PRODUCT MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE. THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING PROFESSIONAL SERVICES. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR YOUR SITUATION. YOU SHOULD CONSULT WITH A SPECIALIST WHERE APPROPRIATE. FURTHER, READERS SHOULD BE AWARE THAT WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ. NEITHER THE PUBLISHER NOR AUTHORS SHALL BE LIABLE FOR ANY LOSS OF PROFIT OR ANY OTHER COMMERCIAL DAMAGES, INCLUDING BUT NOT LIMITED TO SPECIAL, INCIDENTAL, CONSEQUENTIAL, OR OTHER DAMAGES.
For general information on our other products and services, please contact our Customer Care Department within the U.S. at 877-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002. For technical support, please visit https://hub.wiley.com/community/support/dummies.
Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with standard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to media such as a CD or DVD that is not included in the version you purchased, you may download this material at http://booksupport.wiley.com. For more information about Wiley products, visit www.wiley.com.
Library of Congress Control Number: 2021951074
ISBN: 978-1-11-983907-1 (pbk)
ISBN 978-1-11-984012-1 (ebk); ISBN 978-1-11-983908-8 (ebk)
Cover
Title Page
Copyright
Introduction
About This Book
Foolish Assumptions
Icons Used in This Book
Beyond the Book
Where to Go from Here
Book 1: The Basics of C# Programming
Chapter 1: Creating Your First C# Console Application
Getting a Handle on Computer Languages, C#, and .NET
Creating Your First Console Application
Making Your Console App Do Something
Reviewing Your Console Application
Replacing All that Ceremonial Code: Top-Level Statements
Introducing the Toolbox Trick
Interacting with C# Online
Working with Jupyter Notebook: The Short Version
Chapter 2: Living with Variability — Declaring Value-Type Variables
Declaring a Variable
What’s an int?
Representing Fractions
Handling Floating-Point Variables
Using the Decimal Type: Is It an Integer or a Float?
Examining the bool Type: Is It Logical?
Checking Out Character Types
What’s a Value Type?
Comparing string and char
Calculating Leap Years: DateTime
Declaring Numeric Constants
Changing Types: The Cast
Letting the C# Compiler Infer Data Types
Chapter 3: Pulling Strings
The Union Is Indivisible, and So Are Strings
Performing Common Operations on a String
Comparing Strings
What If I Want to Switch Case?
Looping through a String
Searching Strings
Getting Input from Users in Console Applications
Controlling Output Manually
Formatting Your Strings Precisely
StringBuilder: Manipulating Strings More Efficiently
Chapter 4: Smooth Operators
Performing Arithmetic
Performing Logical Comparisons — Is That Logical?
Matching Expression Types at TrackDownAMate.com
Chapter 5: Getting into the Program Flow
Branching Out with if and switch
Here We Go Loop-the-Loop
Looping a Specified Number of Times with for
Chapter 6: Lining Up Your Ducks with Collections
The C# Array
Processing Arrays by Using foreach
Sorting Arrays of Data
Using var for Arrays
Loosening Up with C# Collections
Understanding Collection Syntax
Using Lists
Using Dictionaries
Array and Collection Initializers
Using Sets
Chapter 7: Stepping through Collections
Iterating through a Directory of Files
Iterating foreach Collections: Iterators
Accessing Collections the Array Way: Indexers
Looping Around the Iterator Block
Chapter 8: Buying Generic
Writing a New Prescription: Generics
Classy Generics: Writing Your Own
Understanding Variance in Generics
Chapter 9: Some Exceptional Exceptions
Using an Exceptional Error-Reporting Mechanism
Can I Get an Exceptional Example?
Working with Custom Exceptions
Planning Your Exception-Handling Strategy
Grabbing Your Last Chance to Catch an Exception
Throwing Expressions
Chapter 10: Creating Lists of Items with Enumerations
Seeing Enumerations in the Real World
Working with Enumerations
Creating Enumerated Flags
Defining Enumerated Switches
Working with Enumeration Methods
Book 2: Object-Oriented C# Programming
Chapter 1: Showing Some Class
A Quick Overview of Object-Oriented Programming
Defining a Class and an Object
Accessing the Members of an Object
Working with Object-Based Code
Discriminating between Objects
Can You Give Me References?
Classes That Contain Classes Are the Happiest Classes in the World
Generating Static in Class Members
Defining const and readonly Data Members
Chapter 2: We Have Our Methods
Defining and Using a Method
Method Examples for Your Files
Having Arguments with Methods
Using the Call-by-Reference Feature
Defining a Method with No Return Value
Returning Multiple Values Using Tuples
Chapter 3: Let Me Say This about this
Passing an Object to a Method
Comparing Static and Instance Methods
Accessing the Current Object
Using Local Functions
Chapter 4: Holding a Class Responsible
Restricting Access to Class Members
Why You Should Worry about Access Control
Defining Class Properties
Using Target Typing for Your Convenience
Dealing with Covariant Return Types
Getting Your Objects Off to a Good Start — Constructors
Using Expression-Bodied Members
Chapter 5: Inheritance: Is That All I Get?
Why You Need Inheritance
Inheriting from a BankAccount Class (a More Complex Example)
IS_A versus HAS_A — I’m So Confused_A
Other Features That Support Inheritance
Chapter 6: Poly-what-ism?
Overloading an Inherited Method
Polymorphism
C# During Its Abstract Period
Sealing a Class
Chapter 7: Interfacing with the Interface
Introducing CAN_BE_USED_AS
Knowing What an Interface Is
Using an Interface
Using the C# Predefined Interface Types
Looking at a Program That CAN_BE_USED_AS an Example
Unifying Class Hierarchies
Hiding Behind an Interface
Inheriting an Interface
Using Interfaces to Manage Change in Object-Oriented Programs
Chapter 8: Delegating Those Important Events
E.T., Phone Home — The Callback Problem
Defining a Delegate
Pass Me the Code, Please — Examples
A More Real-World Example
Shh! Keep It Quiet — Anonymous Methods
Stuff Happens — C# Events
Chapter 9: Can I Use Your Namespace in the Library?
Dividing a Single Program into Multiple Source Files
Working with Global using Statements
Dividing a Single Program into Multiple Assemblies
Putting Your Classes into Class Libraries
Going Beyond Public and Private: More Access Keywords
Putting Classes into Namespaces
Working with Partial Methods
Chapter 10: Improving Productivity with Named and Optional Parameters
Exploring Optional Parameters
Looking at Named Parameters
Using Alternative Methods to Return Values
Dealing with null Parameters
Chapter 11: Interacting with Structures
Comparing Structures to Classes
Creating Structures
Working with Read-only Structures
Working with Reference Structures
Using Structures as Records
Using the New Record Type
Book 3: Designing for C#
Chapter 1: Writing Secure Code
Designing Secure Software
Building Secure Windows Applications
Using System.Security
Chapter 2: Accessing Data
Getting to Know System.Data
How the Data Classes Fit into the Framework
Getting to Your Data
Using the System.Data Namespace
Chapter 3: Fishing the File Stream
Going Where the Fish Are: The File Stream
StreamWriting for Old Walter
Pulling Them Out of the Stream: Using StreamReader
More Readers and Writers
Exploring More Streams than Lewis and Clark
Chapter 4: Accessing the Internet
Getting to Know System.Net
How Net Classes Fit into the Framework
Using the System.Net Namespace
Chapter 5: Creating Images
Getting to Know System.Drawing
How the Drawing Classes Fit into the Framework
Using the System.Drawing Namespace
Chapter 6: Programming Dynamically!
Shifting C# Toward Dynamic Typing
Employing Dynamic Programming Techniques
Putting Dynamic to Use
Running with the Dynamic Language Runtime
Using Static Anonymous Functions
Book 4: A Tour of Visual Studio
Chapter 1: Getting Started with Visual Studio
Versioning the Versions
Installing Visual Studio
Breaking Down the Projects
Chapter 2: Using the Interface
Designing in the Designer
Paneling the Studio
Coding in the Code Editor
Using the Tools of the Trade
Using the Debugger as an Aid to Learning
Chapter 3: Customizing Visual Studio
Setting Options
Creating Your Own Templates
Book 5: Windows Development with WPF
Chapter 1: Introducing WPF
Understanding What WPF Can Do
Introducing XAML
Diving In! Creating Your First WPF Application
Whatever XAML Can Do, C# Can Do Better!
Chapter 2: Understanding the Basics of WPF
Using WPF to Lay Out Your Application
Arranging Elements with Layout Panels
Exploring Common XAML Controls
Chapter 3: Data Binding in WPF
Getting to Know Dependency Properties
Exploring the Binding Modes
Investigating the Binding Object
Editing, Validating, Converting, and Visualizing Your Data
Finding Out More about WPF Data Binding
Chapter 4: Practical WPF
Commanding Attention
Using Built-In Commands
Using Custom Commands
Using Routed Commands
Chapter 5: Programming for Windows 10 and Above
What is the Universal Windows Platform (UWP)?
Devices Supported by the UWP
Creating Your Own UWP App
Working with .NET Core Applications
Book 6: Web Development with ASP.NET
Chapter 1: Creating a Basic ASP.NET Core App
Understanding the ASP.NET Core Templates
Developing a Basic Web App
Chapter 2: Employing the Razor Markup Language
Avoiding Nicks from Razor
Creating Variables
Keeping Things Logical
Implementing Loops
Chapter 3: Generating and Consuming Data
Understanding Why These Projects Are Important
Serialized Data Isn’t for Breakfast
Developing a Data Generator and API
Creating a Consumer Website
Index
About the Author
Advertisement Page
Connect with Dummies
End User License Agreement
Book 1 Chapter 2
TABLE 2-1 Size and Range of C# Integer Types
TABLE 2-2 Size and Range of Floating-Point Variable Types
TABLE 2-3 Special Characters
TABLE 2-4 Common Constants Declared along with Their Types
Book 1 Chapter 3
TABLE 3-1 Format Specifiers Using String.Format()
Book 1 Chapter 4
TABLE 4-1 Simple Operators
TABLE 4-2 Logical Comparison Operators
TABLE 4-3 The Compound Logical Operators
Book 1 Chapter 6
TABLE 6-1 The Most Common Collection “Shapes”
Book 1 Chapter 8
TABLE 8-1 Generic Constraint Options
Book 3 Chapter 1
TABLE 1-1 Common Namespaces in System.Security
Book 3 Chapter 2
TABLE 2-1 The System.Data Namespaces
Book 3 Chapter 4
TABLE 4-1 A Listing of Important System.Net-Associated Namespaces
Book 1 Chapter 1
FIGURE 1-1: Creating a new project starts you down the road to a better Windows...
FIGURE 1-2: The Visual Studio App Wizard is eager to create a new program for y...
FIGURE 1-3: The Visual Studio App Wizard is eager to create a new program for y...
FIGURE 1-4: Visual Studio displays the project you just created.
FIGURE 1-5: Changing the default project location.
Book 1 Chapter 6
FIGURE 6-1: The term
swapping two objects
means swapping
references
to two obje...
Book 1 Chapter 7
FIGURE 7-1: Adding a path for the files to list.
Book 1 Chapter 9
FIGURE 9-1: Where, oh where can a handler be found?
FIGURE 9-2: Providing XML comments for your methods.
Book 2 Chapter 1
FIGURE 1-1: Two references to the same object.
Book 2 Chapter 2
FIGURE 2-1: Obtaining a copy of
Program.cs
from the
CalculateInterestTableMoreF
...
FIGURE 2-2: The IDE will tell you what is wrong with the passing of arguments.
FIGURE 2-3: Visual Studio tells you about the default method parameter values.
Book 2 Chapter 6
FIGURE 6-1: A UML description of the
HighSchool
and
University
classes.
FIGURE 6-2: Inheriting
HighSchool
simplifies the
University
class but introduce...
FIGURE 6-3: Base both
HighSchool
and
University
on a common
School
class.
FIGURE 6-4: Class factoring usually results in added layers of inheritance hier...
FIGURE 6-5: Breaking down classes is partially a function of the problem being ...
Book 2 Chapter 7
FIGURE 7-1: A tale of two class hierarchies and one interface.
Book 2 Chapter 8
FIGURE 8-1: Sending your delegate to the bungee-jump on your behalf.
FIGURE 8-2: Choose the Windows Forms App (.NET Framework) template.
FIGURE 8-3: The Common Controls Group contains the controls you use most often.
FIGURE 8-4: Create the form you use to demonstrate the use of a progress bar.
Book 2 Chapter 9
FIGURE 9-1: Use the Add New Item dialog box to add a new item to your project.
FIGURE 9-2: The Class Library (.NET Framework) is for use with Windows alone.
FIGURE 9-3: Configure the class as needed.
FIGURE 9-4: Configure the options for the application used to test the
DoMath
c...
FIGURE 9-5: Organizing two projects in an all-in-one-folder.
FIGURE 9-6: Organizing two projects side by side.
FIGURE 9-7: The projects used to create the TestClass solution are listed indiv...
FIGURE 9-8: Add a reference for your class library.
Book 3 Chapter 1
FIGURE 1-1: The Windows Security application sample.
FIGURE 1-2: The WindowsSecurity tab of the My Project configuration file.
Book 3 Chapter 2
FIGURE 2-1: Choose a source type for the application data.
FIGURE 2-2: Choose a database model to use to model the data.
FIGURE 2-3: Choosing your data connection.
FIGURE 2-4: The Choose Data Source dialog box.
FIGURE 2-5: Specify the location of the database file used for this example.
FIGURE 2-6: Selecting data objects.
FIGURE 2-7: Table Options drop-down list.
FIGURE 2-8: Creating a Parts Detail data form.
FIGURE 2-9: Generated code. Huh?
Book 3 Chapter 4
FIGURE 4-1: Many controls come with SmartTags that let you configure them easil...
FIGURE 4-2: Configure the
StatusStrip
to provide the user with useful informati...
FIGURE 4-3: Configuring the form to accept email information.
Book 3 Chapter 5
FIGURE 5-1: A traditional cribbage board.
FIGURE 5-2: The digital cribbage board.
FIGURE 5-3: The basic board.
FIGURE 5-4: Add a Leave event handler for each of the TextBox controls.
Book 3 Chapter 6
FIGURE 6-1: The Dynamic Language Runtime.
Book 4 Chapter 1
FIGURE 1-1: The Visual Studio Community edition provides lots of project types.
FIGURE 1-2: Solutions and projects appear in Solution Explorer.
Book 4 Chapter 2
FIGURE 2-1: Creating a UWP application is a process that Visual Studio helps wi...
FIGURE 2-2: UWP applications rely on the use of pages to display information.
FIGURE 2-3: The WPF Designer.
FIGURE 2-4: The Windows Forms Designer.
FIGURE 2-5: When you use Data View, who needs SQL Management Studio?
FIGURE 2-6: The explorer of solutions.
FIGURE 2-7: Modifying object properties.
FIGURE 2-8: The Toolbox, with tools.
FIGURE 2-9: Server Explorer.
FIGURE 2-10: A view with Class.
FIGURE 2-11: The Breakpoints window.
FIGURE 2-12: Executing to a line of code.
FIGURE 2-13: Use the Locals window to see local variable values.
FIGURE 2-14: Use the Watch window to create custom variable views.
Book 4 Chapter 3
FIGURE 3-1: The default Options screen.
FIGURE 3-2: Determine whether you want to create a project or item template.
FIGURE 3-3: Provide enough information for others to use your template.
FIGURE 3-4: Your template will normally appear first in the list after you remo...
FIGURE 3-5: Determine which item to export from the project.
FIGURE 3-6: Select the references needed to use your item successfully.
Book 5 Chapter 1
FIGURE 1-1: A typical combo box.
FIGURE 1-2: Visualizing data — a WPF combo box.
FIGURE 1-3: Configuring the WPF project.
FIGURE 1-4: WPF Application solution structure.
Book 5 Chapter 2
FIGURE 2-1: Vertical Stack panel.
FIGURE 2-2: Horizontal layout showing clipped content.
FIGURE 2-3: Two
Wrappanel
s housed in a
StackPanel
.
FIGURE 2-4: A Dock panel fills in controls in the area specified in XAML order.
FIGURE 2-5: Canvas sample.
FIGURE 2-6: Basic
Grid
with proportional (
*
) row heights.
FIGURE 2-7: Grid with row and column spans.
FIGURE 2-8: An example using
Margin
and
Padding
.
FIGURE 2-9: Multiple
Grid
s with shared sizing.
FIGURE 2-10: Simple data entry form.
FIGURE 2-11: Display-only controls.
FIGURE 2-12: All the basic input controls.
FIGURE 2-13: The
ComboBox
(left),
ListBox
(center), and
TreeView
(right) contro...
Book 5 Chapter 3
FIGURE 3-1: Data binding to properties of a
DataContext
.
FIGURE 3-2: Editing data using a TwoWay binding mode.
FIGURE 3-3: TwoWay data binding with
INotifyPropertyChanged
.
FIGURE 3-4: Displaying error messages using Styles.
FIGURE 3-5: Rendering a collection of data using a value converter and data tem...
Book 5 Chapter 4
FIGURE 4-1: Using the Copy and Paste features of the application.
FIGURE 4-2: Selecting the text enables the Copy button.
FIGURE 4-3: Typing a name (or other text) enables both the button and the menu.
FIGURE 4-4: Clicking either control produces simple output.
Book 5 Chapter 5
FIGURE 5-1: You can’t create a UWP app without setting Developer Mode on.
FIGURE 5-2: Microsoft warns you about the possible problems in enabling Develop...
FIGURE 5-3: Make sure that local group policies don't get in the way of sideloa...
FIGURE 5-4: Using the search field on the taskbar makes it easy to find the Dev...
FIGURE 5-5: The Settings app provides an overview of developer-related settings...
FIGURE 5-6: The actual settings for Developer Mode appear in a number of places...
FIGURE 5-7: Use the Remote Desktop settings with care.
FIGURE 5-8: A listing of UWP templates.
FIGURE 5-9: A UWP project requires some additional configuration.
FIGURE 5-10: After completing the project wizard, you see a list of development...
FIGURE 5-11: The app interface is very flexible and should work well for most d...
FIGURE 5-12: The example app shown in a 13.5” Surface Book (3000 x 2000) form.
FIGURE 5-13: The example app shown in a 6” Phone (1920 x 1080) form.
FIGURE 5-14: The Run button includes options for alternative deployments.
FIGURE 5-15: Locating the .NET Core templates is made easier using a search.
Book 6 Chapter 1
FIGURE 1-1: Even an empty template provides you with a considerable number of f...
FIGURE 1-2: The version of .NET and app features both contribute to the file st...
FIGURE 1-3: The Web App template provides you with basic content as a starting ...
FIGURE 1-4: Use the generated SSL certificate or install your own.
FIGURE 1-5: You must install any certificate you use in Windows as well as Visu...
FIGURE 1-6: Separating functionality in MVC means yet more files.
FIGURE 1-7: The ASP.NET Core Web API focuses on the API, not the client.
FIGURE 1-8: Configure your new project with identifying information.
FIGURE 1-9: The example uses fewer template features to reduce project complexi...
FIGURE 1-10: Add a new item to the wwwroot folder.
Book 6 Chapter 3
FIGURE 3-1: Locate the ASP.NET Core Web API template.
FIGURE 3-2: Provide a name and location for the API.
FIGURE 3-3: Select the additional requirements for the API.
FIGURE 3-4: Determine whether you want to install the SSL certificate.
FIGURE 3-5: Make Windows feel better by answering the question a second time.
FIGURE 3-6: The browser output shows serialized weather forecast data.
FIGURE 3-7: Look for the IIS Express icon in the Notification Area to see which...
FIGURE 3-8: Stop the site so that you can see changes to your user-interface co...
FIGURE 3-9: Add the
WeatherForecast
class to your project.
FIGURE 3-10: See the generated weather forecast from the
WeatherForecast
API.
Cover
Title Page
Copyright
Table of Contents
Begin Reading
Index
About the Author
iii
iv
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
81
82
83
84
85
86
87
88
89
90
91
92
93
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
229
230
231
232
233
234
235
236
237
238
239
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
639
640
641
642
643
644
645
646
647
648
649
650
651
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
833
835
836
C# is an amazing language that is currently ranked the fifth most popular language in the world, according to the Tiobe Index (https://www.tiobe.com/tiobe-index/)! You can use this single language to do everything from desktop development to creating web applications and even web-based application programming interfaces (APIs). In addition, C# now makes it possible to target a multitude of platforms, including macOS and Linux. While other developers have to overcome deficiencies in their languages to create even a subset of the application types that C# supports with aplomb, you can be coding your application, testing, and then sitting on the beach enjoying the fruits of your efforts. Of course, any language that does this much requires a bit of explanation, and C# 10.0 All-in-One For Dummies is your doorway to this new adventure in development.
So, why do you need C# 10.0 All-in-One For Dummies specifically? This book stresses learning the basics of the C# language before you do anything else. With this in mind, the book begins with all the C# basics in Books 1 through 3, helps you get Visual Studio 2022 installed in Book 4, and then takes you through more advanced development tasks, including basic web development, in Books 5 through 6. Using this book helps you get the most you can from C# 10.0 in the least possible time.
Even if you have past experience with C#, the new features in C# 10.0 will have you producing feature-rich applications in an even shorter time than you may have before. C# 10.0 All-in-One For Dummies introduces you to all these new features. For example, you discover how to work with both Universal Windows Platform (UWP) and Windows 10 and above applications (besides using all the old standbys). You also find all the new features provided for object-oriented development, and new IDE features designed to make your development experience easier. Make sure you don’t miss out on the new Record type discussed in Book 2, Chapter 11. This book is designed to make using C# 10.0 fast and easy; it removes the complexity that you may have experienced when trying to learn about these topics online.
To help you absorb the concepts, this book uses the following conventions:
Text that you're meant to type just as it appears in the book is in
bold
. The exception is when you’re working through a step list: Because each step is bold, the text to type is not bold.
Words for you to type that are also in
italics
are meant as placeholders; you need to replace them with something that works for you. For example, if you see “Type
Your Name
and press Enter,” you need to replace
Your Name
with your actual name.
I also use
italics
for terms I define. This means that you don’t have to rely on other sources to provide the definitions you need.
Web addresses and programming code appear in
monofont
. If you’re reading a digital version of this book on a device connected to the Internet, you can click the live link to visit a website, like this:
www.dummies.com
.
When you need to click command sequences, you see them separated by a special arrow, like this: File ⇒ New File, which tells you to click File and then click New File.
You might have a hard time believing that I’ve assumed anything about you — after all, I haven’t even met you yet! Although most assumptions are indeed foolish, I made certain assumptions to provide a starting point for the book.
The most important assumption is that you know how to use Windows, have a copy of Windows properly installed, and are familiar with using Windows applications. Even though this book covers developing applications that run on multiple platforms, the development environment always assumes that you’re working with Windows. If installing an application is still a mystery to you, you might find this book a bit hard to use. While reading this book, you need to install applications, discover how to use them, and create simple applications of your own.
You also need to know how to work with the Internet. Many of the materials, including the downloadable source, appear online, and you need to download them in order to get the maximum value from the book. In addition, Book 6 assumes that you have a certain knowledge of the Internet when working through web-based applications and web-based services.
As you read this book, you encounter icons in the margins that indicate material of special interest (or not, as the case may be!). Here’s what the icons mean:
Tips are nice because they help you save time or perform some task without a lot of extra work. The tips in this book are time-saving techniques or pointers to resources that you should try so that you can get the maximum benefit when performing C#-related tasks.
I don’t want to sound like an angry parent or some kind of maniac, but you should avoid doing anything that’s marked with a Warning icon. Otherwise, you might find that your configuration fails to work as expected, you get incorrect results from seemingly bulletproof processes, or (in the worst-case scenario) you lose data.
Whenever you see this icon, think advanced tip or technique. You might find these tidbits of useful information just too boring for words, or they could contain the solution you need to get a C# application running. Skip these bits of information whenever you like.
If you don’t get anything else out of a particular chapter or section, remember the material marked by this icon. This text usually contains an essential process or a bit of information that you must know to work with C#.
This book isn’t the end of your C# learning experience — it’s really just the beginning. I provide online content to make this book more flexible and better able to meet your needs. Also, you can send me e-mail at [email protected]. I’ll address your book-specific questions and tell you how updates to C# or its associated add-ons affect book content through blog posts. Here are some cool online additions to this book:
Cheat sheet:
You remember using crib notes in school to make a better mark on a test, don’t you? You do? Well, a cheat sheet is sort of like that. It provides you with some special notes about tasks that you can do with C# that not every other person knows. To find the cheat sheet for this book, go to
www.dummies.com
and search for
C# 10.0 All-in-One For Dummies Cheat Sheet.
It contains really neat information such as how to figure out which template you want to use.
Updates: Sometimes changes happen. For example, I might not have seen an upcoming change when I looked into my crystal ball during the writing of this book. In the past, this possibility simply meant that the book became outdated and less useful, but you can now find updates to the book at www.dummies.com.
In addition to these updates, check out the blog posts with answers to reader questions and demonstrations of useful book-related techniques at http://blog.johnmuellerbooks.com/.
Companion files:
Hey! Who really wants to type all the code in the book manually? Most readers prefer to spend their time actually working with C#, creating amazing new applications that change the world, and seeing the interesting things they can do, rather than typing. Fortunately for you, the examples used in the book are available for download, so all you need to do is read the book to learn C# development techniques. You can find these files at
www.dummies.com
and at
http://www.johnmuellerbooks.com/source-code/
.
Anyone who is unfamiliar with C# should start with Book 1, Chapter 1 and move from there to the end of the book. This book is designed to make it easy for you to discover the benefits of using C# from the outset. Later, after you’ve seen enough C# code, you can install Visual Studio and then try the programming examples found in the first three minibooks. (Note that Book 1, Chapter 1 provides a brief overview of using Jupyter Notebook instead of Visual Studio 2022, but many of the new examples won’t work with this setup.)
This book assumes that you want to see C# code from the outset. However, if you want to interact with that code, you really need to have a copy of Visual Studio 2022 installed. (Some examples will not work at all with older Visual Studio versions.) With this in mind, you may want to skip right to Book 4 to discover how to get your own copy of Visual Studio 2022. To help ensure that everyone can participate, this book focuses on the features offered by Visual Studio 2022 Community Edition, which is a free download. That’s right, you can discover the wonders of C# 10.0 without paying a dime!
The more you know about C#, the later you can start in the book. If all you’re really interested in is an update of your existing skills, check out Book 1, Chapter 1 to discover the changes in C#. Then, scan the first three minibooks looking for points of interest. Install C# by using the instructions in Book 4, Chapter 1, and then move on toward the advanced techniques found in later chapters. You definitely don’t want to miss out on the Windows 10 and above development topics in Book 5, Chapter 5. In addition, Book 6 is entirely new for this edition, so even if you saw the previous edition of the book, you don’t want to miss out on this new content.
Book 1
Chapter 1: Creating Your First C# Console Application
Getting a Handle on Computer Languages, C#, and .NET
Creating Your First Console Application
Making Your Console App Do Something
Reviewing Your Console Application
Replacing All that Ceremonial Code: Top-Level Statements
Introducing the Toolbox Trick
Interacting with C# Online
Working with Jupyter Notebook: The Short Version
Chapter 2: Living with Variability — Declaring Value-Type Variables
Declaring a Variable
What’s an int?
Representing Fractions
Handling Floating-Point Variables
Using the Decimal Type: Is It an Integer or a Float?
Examining the bool Type: Is It Logical?
Checking Out Character Types
What’s a Value Type?
Comparing string and char
Calculating Leap Years: DateTime
Declaring Numeric Constants
Changing Types: The Cast
Letting the C# Compiler Infer Data Types
Chapter 3: Pulling Strings
The Union Is Indivisible, and So Are Strings
Performing Common Operations on a String
Comparing Strings
What If I Want to Switch Case?
Looping through a String
Searching Strings
Getting Input from Users in Console Applications
Controlling Output Manually
Formatting Your Strings Precisely
StringBuilder: Manipulating Strings More Efficiently
Chapter 4: Smooth Operators
Performing Arithmetic
Performing Logical Comparisons — Is That Logical?
Matching Expression Types at TrackDownAMate.com
Chapter 5: Getting into the Program Flow
Branching Out with if and switch
Here We Go Loop-the-Loop
Looping a Specified Number of Times with for
Chapter 6: Lining Up Your Ducks with Collections
The C# Array
Processing Arrays by Using foreach
Sorting Arrays of Data
Using var for Arrays
Loosening Up with C# Collections
Understanding Collection Syntax
Using Lists
Using Dictionaries
Array and Collection Initializers
Using Sets
Chapter 7: Stepping through Collections
Iterating through a Directory of Files
Iterating foreach Collections: Iterators
Accessing Collections the Array Way: Indexers
Looping Around the Iterator Block
Chapter 8: Buying Generic
Writing a New Prescription: Generics
Classy Generics: Writing Your Own
Understanding Variance in Generics
Chapter 9: Some Exceptional Exceptions
Using an Exceptional Error-Reporting Mechanism
Can I Get an Exceptional Example?
Working with Custom Exceptions
Planning Your Exception-Handling Strategy
Grabbing Your Last Chance to Catch an Exception
Throwing Expressions
Chapter 10: Creating Lists of Items with Enumerations
Seeing Enumerations in the Real World
Working with Enumerations
Creating Enumerated Flags
Defining Enumerated Switches
Working with Enumeration Methods
Chapter 1
IN THIS CHAPTER
Getting a quick introduction to programming
Creating and examining a simple console application
Saving code for later
Working online and in other environments
A console application is one that you run at the command prompt; it doesn’t rely on any sort of fancy GUI to provide a pretty interface. Console applications are useful for all sorts of utilitarian tasks, and many people with low-level computer knowledge prefer them because they’re extremely efficient to use. However, many people use console applications without even knowing it because console applications often play a role in configuration tasks. Because console applications are also easier to write than any other application type, you see them used quite often to demonstrate general C# (pronounced see-sharp) coding principles that really matter, like saying, “Hello World!”
Part of working with code is knowing how to perform basic tasks using the Integrated Development Environment (IDE). For example, you need to know how to create a new application and then save it to disk when you’re done. This book assumes that you’re using Visual Studio 2022 Community Edition. However, you might want to be different and use something else. That’s why you see the IDEs for different people at the end of the chapter. Oddly enough, you can use some of these IDEs with your mobile device. Why write application code in your stuffy office when you can bask in the Maui sun?
You don’t have to type the source code for this chapter manually. In fact, using the downloadable source is a lot easier. You can find the source for this chapter in the \CSAIO4D2E\BK01\CH01 folder of the downloadable source. See the Introduction for details on how to find these source files.
Computers will do anything you ask them to (within reason). They do it extremely fast, and they're getting faster all the time. Unfortunately, computers don’t understand anything that resembles a human language. Oh, you may come back and say something like, “Hey, my telephone lets me dial my friend by just speaking a name.” Yes, a tiny computer runs your telephone, but that’s a computer program that parses English into tokens that the computer matches to patterns of things to do. Never does the computer understand English or whatever other language you speak.
The language that computers truly understand is machine language. It’s possible for humans to write machine code directly, but doing so is extremely difficult and error prone. So, programmers developed languages that are easier for people to use but are easily translated into machine code. The languages occupying this middle ground — C#, for example — are high-level computer languages. (High is a relative term here.)
What is a program? In a practical sense, a Windows program is an executable file that you can run by double-clicking its icon. For example, Microsoft Word, the editor used to write this book, is a program. You call that an executable program, or executable for short. The names of executable program files generally end with the extension .exe. Word, for example, is Winword.exe.
But a program is something else as well. An executable program consists of one or more source files. A C# source file, for instance, is a text file that contains a sequence of C# commands that fit together according to the laws of C# grammar. This file is known as a source file probably because it's a source of frustration and anxiety.
Uh, grammar? There’s going to be grammar? Just the C# kind, which is much easier than the kind most people struggled with in junior high school.
Programmers use the C# programming language to create executable programs. C# combines the range of the powerful but complicated C++ (pronounced see plus plus) with the ease of use of the friendly but more verbose Visual Basic. A C# program file carries the extension .cs. Some people have pointed out that C sharp and D flat are the same note, but you shouldn't refer to this new language as D flat within earshot of Redmond, Washington. C# is
Flexible:
C# programs can execute on the current machine, or they can be transmitted over the web and executed on some distant computer.
Powerful:
C# has essentially the same command set as C++ but with the rough edges filed smooth.
Easier to use:
C# error-proofs the commands responsible for most C++ errors, so you spend far less time chasing down those errors.
Visually oriented:
The .NET code library that C# uses for many of its capabilities provides the help needed to create complicated display frames with the controls commonly seen in specific environments such as the desktop, using technologies like Windows Forms, Windows Presentation Foundation (WPF), and Universal Application Platform (UAP).
Internet-friendly:
C# plays a pivotal role in the .NET Framework, Microsoft’s current approach to programming for Windows, the Internet, and beyond.
Secure:
Any language intended for use on the Internet must include serious security to protect against malevolent hackers.
Finally, C# is an integral part of .NET (which includes the .NET Framework, .NET Core, and other elements of the .NET ecosystem).
This book is primarily about the C# language. If your primary goal is to use Visual Studio, program Windows 8 or 10 apps, or ASP.NET, the For Dummies books on those topics go well with this book; go to www.dummies.com to find them. You can find a good amount of information later in this book on how to use C# to write traditional Windows, WPF, UAP, web, and service applications.
Think of .NET as the foundation of the application you want to build. It contains all the low-level features you need to create an application, but C# builds on to that foundation to make development easier. .NET began as Microsoft’s strategy to open the web to mere mortals like you and me. Today, it encompasses everything Microsoft does. In particular, it’s the way to program for Windows and other platforms. It also gives C# the visual tools that made Visual Basic so popular. For the purposes of this book, .NET includes these subelements:
.NET Framework:
This is the Windows-only, feature-complete version of .NET that you use for the majority of the book’s examples.
.NET Core:
This is the multiplatform, less functional version of .NET that you use to implement some C# 9,0 and C# 10.0 features. It allows you to use the same application on Windows, Linux, macOS, and mobile devices (via Xamarin). The article at
https://stackify.com/net-core-vs-net-framework/
provides a great overview of the differences between the .NET Framework and .NET Core, but this book tells you about them from a real-world perspective.
(You sure ask lots of questions.) The first “Visual” language from Microsoft was Visual Basic. The first popular C-based language from Microsoft was Visual C++. Like Visual Basic, it had Visual in its name because it had a built-in graphical user interface (GUI — pronounced “GOO-ee”). This GUI included everything you needed to develop C++ programs.
Eventually, Microsoft rolled all its languages into a single environment — Visual Studio. As Visual Studio 6.0 started getting a little long in the tooth, developers anxiously awaited version 7. Shortly before its release, however, Microsoft decided to rename it Visual Studio .NET to highlight this new environment’s relationship to the .NET Framework (.NET Core wasn’t available then).
That sounded like a marketing ploy to a lot of people — until they started delving into it. Visual Studio .NET differed quite a bit from its predecessors — enough to warrant a new name. Visual Studio 2022 is the eleventh-generation successor to the original Visual Studio .NET. (Book 4 is full of Visual Studio goodness, including instructions for customizing it. You may want to use the instructions in Book 4, Chapter 1 to install a copy of Visual Studio before you get to the example later in this chapter. If you’re completely unfamiliar with Visual Studio, reviewing all of Book 4 is helpful.)
Visual Studio 2022 includes an Application Wizard that builds template programs and saves you a lot of the dirty work you’d have to do if you did everything from scratch. (The from-scratch approach is error prone, to say the least.)
Typically, starter programs don’t really do anything — at least, not anything useful. However, they do get you beyond that initial hurdle of getting started. Some starter programs are reasonably sophisticated. In fact, you’ll be amazed at how much capability the App Wizard can build on its own, especially for graphical programs.
The following instructions are for Visual Studio 2019 configured for C# development. (There are other configurations you can use, including a general configuration if you use a number of languages.) If you use anything other than Visual Studio, you have to refer to the documentation that came with your environment, such as Jupyter Notebook (described in the “Working with Jupyter Notebook: The Short Version” section, near the end of the chapter). Alternatively, you can just type the source code directly into your C# online environment (described in the “Interacting with C# Online” section, later in this chapter).
To start Visual Studio, press the Windows button on your keyboard and type Visual Studio. Visual Studio 2022 appears as one of the available options. Complete these steps to create your C# console app:
Open Visual Studio 2022.
You see a list of options, as shown in Figure 1-1. (If this is the first time you’ve used Visual Studio 2022, you won’t see any recent files and you may also see an additional Get Started option or two.) Notice that you can connect to various source code locations, open a recently opened project or solution, or create something new.
Click the Create a New Project link.
You see a rather long and confusing list of project types. However, you can easily prune away the projects you don't want.
Select C# in the Language drop-down list box, Windows in the Platform drop-down list box, and Console in the Project Type drop-down list box.
Visual Studio presents you with entries representing the different types of applications you can create, as shown in Figure 1-2. Notice that each entry shows a language and the platforms that it supports.
FIGURE 1-1: Creating a new project starts you down the road to a better Windows application.
FIGURE 1-2: The Visual Studio App Wizard is eager to create a new program for you.
In the Create a New Project window, select the Console App (.NET Framework) entry.
Visual Studio requires you to create a project before you can start entering your C# program. A project is a folder into which you throw all the files that go into making your program. It has a set of configuration files that help the compiler do its work. When you tell your compiler to build (compile) the program, it sorts through the project to find the files it needs in order to re-create the executable program.
Visual Studio 2022 provides support for both .NET Framework and .NET Core applications. A .NET Framework application is the same as the C# applications supported in previous versions of Windows; it runs only in Windows and isn’t open source. A .NET Core application can run in Windows, Linux, and Mac environments and relies on an open source setup. Although using .NET Core may seem ideal, the .NET Core applications also support only a subset of the .NET Framework features, and you can’t add a GUI to them. Microsoft created the .NET Core for these uses:
Cross-platform development
Microservices
Docker containers
High performance and scalable applications
Side-by-side .NET application support
Click Next.
You see a Configure Your New Project dialog box, as shown in Figure 1-3. This is where you tell the wizard how to create the basics of your application.
The default name for your first application isConsoleApp1, but change it this time to Program1 by typing in the Name field.
The default place to store this file is somewhere deep in your Documents directory. For most developers, it's a lot better to place the files where you can actually find them and interact with them as needed, not necessarily where Visual Studio wants them.
Type C:\CSAIO4D2E\BK01\CH01 in the Location field to change the location of this project.
If you don’t have permission to create folders in the root directory of your drive where they’re easy to access, create the same folder on your desktop by typing C:\Users\<Your Username>\Desktop\CSAIO4D2E\BK01\CH01. The point is to make your source code easy to access, and the default setting doesn’t do that very well — it hides things.
FIGURE 1-3: The Visual Studio App Wizard is eager to create a new program for you.
Select Place Solution and Project in the Same Directory.
You use this option to make solutions that contain just one project simpler. A solution is a container for multiple projects when you want to create a complex application. For example, you might want to create a console application that also includes a special library contained in a .dll file.
Click the Create button.
After a bit of disk whirring and chattering, Visual Studio generates a file named Program.cs. (If you look in the window labeled Solution Explorer, shown in Figure 1-4, you see some other files; ignore them for now. If Solution Explorer isn't visible, choose View ⇒ Solution Explorer.)
C# source files carry the extension .cs. The name Program is the default name assigned for the program file.
The contents of your first console app appear this way (as shown in Figure 1-4):
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Program1{ class Program{ static void Main(string[] args) { } }}
FIGURE 1-4: Visual Studio displays the project you just created.
You can manually change the location of the project with every project. However, you have a simpler way to go. When working with this book, you can change the default program location. To make that happen, follow these steps after you finish creating the project:
Choose Tools ⇒ Options.
The Options dialog box opens.
Choose Projects and Solutions ⇒ Locations.
Select the new location in the Project Location field and click OK.
(The examples assume that you have used C:\CSAIO4D2E for this book.)
You can see the Options dialog box in Figure 1-5. Leave the other fields in the project settings alone for now. Read more about customizing Visual Studio in Book 4.
FIGURE 1-5: Changing the default project location.
Along the left edge of the code window, you see several small minus signs (–) in boxes. Click the minus sign next to the first using statement, and all the using statements collapse into a using … entry with a plus sign (+) next to it. Click the plus sign next to using …. This expands a code region,