35,99 €
Get a running start to learning C# programming with this fun and easy-to-read guide As one of the most versatile and powerful programming languages around, you might think C# would be an intimidating language to learn. It doesn't have to be! In Beginning C# and .NET: 2021 Edition, expert Microsoft programmer and engineer Benjamin Perkins and program manager Jon D. Reid walk you through the precise, step-by-step directions you'll need to follow to become fluent in the C# language and .NET. Using the proven WROX method, you'll discover how to understand and write simple expressions and functions, debug programs, work with classes and class members, work with Windows forms, program for the web, and access data. You'll even learn about some of the new features included in the latest releases of C# and .NET, including data consumption, code simplification, and performance. The book also offers: * Detailed discussions of programming basics, like variables, flow control, and object-oriented programming that assume no previous programming experience * "Try it Out" sections to help you write useful programming code using the steps you've learned in the book * Downloadable code examples from wrox.com Perfect for beginning-level programmers who are completely new to C#, Beginning C# and .NET: 2021 Edition is a must-have resource for anyone interested in learning programming and looking for a fun and intuitive place to start.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 1239
Veröffentlichungsjahr: 2021
COVER
TITLE PAGE
INTRODUCTION
WHO THIS BOOK IS FOR
WHAT THIS BOOK COVERS
HOW THIS BOOK IS STRUCTURED
WHAT YOU NEED TO USE THIS BOOK
CONVENTIONS
SOURCE CODE
ERRATA
PART I: The C# Language
1 Introducing C#
WHAT IS .NET?
WHAT IS C#?
VISUAL STUDIO
▸ WHAT YOU LEARNED IN THIS CHAPTER
2 Writing a C# Program
THE VISUAL STUDIO DEVELOPMENT ENVIRONMENT
CONSOLE APPLICATIONS
DESKTOP APPLICATIONS
▸ WHAT YOU LEARNED IN THIS CHAPTER
3 Variables and Expressions
BASIC C# SYNTAX
BASIC C# CONSOLE APPLICATION STRUCTURE
VARIABLES
EXPRESSIONS
EXERCISES
▸ WHAT YOU LEARNED IN THIS CHAPTER
4 Flow Control
BOOLEAN LOGIC
BRANCHING
LOOPING
▸ WHAT YOU LEARNED IN THIS CHAPTER
5 More about Variables
TYPE CONVERSION
COMPLEX VARIABLE TYPES
STRING MANIPULATION
▸ WHAT YOU LEARNED IN THIS CHAPTER
6 Functions
DEFINING AND USING FUNCTIONS
VARIABLE SCOPE
THE MAIN() FUNCTION
STRUCT FUNCTIONS
OVERLOADING FUNCTIONS
USING DELEGATES
▸ WHAT YOU LEARNED IN THIS CHAPTER
7 Debugging and Error Handling
DEBUGGING IN VISUAL STUDIO
ERROR HANDLING
▸ WHAT YOU LEARNED IN THIS CHAPTER
8 Introduction to Object-Oriented Programming
WHAT IS OBJECT-ORIENTED PROGRAMMING?
OOP TECHNIQUES
OOP IN DESKTOP APPLICATIONS
▸ WHAT YOU LEARNED IN THIS CHAPTER
9 Defining Classes
CLASS DEFINITIONS IN C#
SYSTEM.OBJECT
CONSTRUCTORS AND DESTRUCTORS
OOP TOOLS IN VISUAL STUDIO
CLASS LIBRARY PROJECTS
INTERFACES VERSUS ABSTRACT CLASSES
STRUCT TYPES
SHALLOW COPYING VERSUS DEEP COPYING
▸ WHAT YOU LEARNED IN THIS CHAPTER
10 Defining Class Members
MEMBER DEFINITIONS
ADDITIONAL CLASS MEMBER TOPICS
INTERFACE IMPLEMENTATION
PARTIAL CLASS DEFINITIONS
PARTIAL METHOD DEFINITIONS
EXAMPLE APPLICATION
THE CALL HIERARCHY WINDOW
▸ WHAT YOU LEARNED IN THIS CHAPTER
11 Collections, Comparisons, and Conversions
COLLECTIONS
COMPARISONS
CONVERSIONS
▸ WHAT YOU LEARNED IN THIS CHAPTER
12 Generics
WHAT ARE GENERICS?
USING GENERICS
DEFINING GENERIC TYPES
VARIANCE
EXERCISES
▸ WHAT YOU HAVE LEARNED IN THIS CHAPTER
13 Additional C# Techniques
THE :: OPERATOR AND THE GLOBAL NAMESPACE QUALIFIER
CUSTOM EXCEPTIONS
EVENTS
EXPANDING AND USING CARDLIB
ATTRIBUTES
INITIALIZERS
TYPE INFERENCE
ANONYMOUS TYPES
DYNAMIC LOOKUP
ADVANCED METHOD PARAMETERS
LAMBDA EXPRESSIONS
▸ WHAT YOU LEARNED IN THIS CHAPTER
PART II: Data Access
14 Files
FILE CLASSES FOR INPUT AND OUTPUT
STREAMS
MONITORING THE FILE SYSTEM
▸ WHAT YOU LEARNED IN THIS CHAPTER
15 XML and JSON
XML BASICS
JSON BASICS
XML SCHEMAS
XML DOCUMENT OBJECT MODEL
SEARCHING XML WITH XPATH
JSON SERIALIZATION AND DESERIALIZATION
▸ WHAT YOU LEARNED IN THIS CHAPTER
16 LINQ
LINQ TO XML
LINQ PROVIDERS
LINQ QUERY SYNTAX
LINQ METHOD SYNTAX
ORDERING QUERY RESULTS
UNDERSTANDING THE ORDERBY CLAUSE
QUERYING A LARGE DATA SET
USING AGGREGATE OPERATORS
USING THE SELECT DISTINCT QUERY
ORDERING BY MULTIPLE LEVELS
USING GROUP QUERIES
USING JOINS
EXERCISES
▸ WHAT YOU LEARNED IN THIS CHAPTER
17 Databases
USING DATABASES
ENTITY FRAMEWORK
CODE-FIRST VERSUS DATABASE-FIRST
MIGRATIONS AND SCAFFOLDING
INSTALL SQL SERVER EXPRESS LOCALDB
A CODE-FIRST DATABASE
EXPLORING YOUR DATABASE
NAVIGATING DATABASE RELATIONSHIPS
CREATING AND QUERYING XML FROM AN EXISTING DATABASE
▸ WHAT YOU LEARNED IN THIS CHAPTER
PART III: Additional Techniques
18 .NET and ASP.NET
CROSS-PLATFORM BASICS AND KEY “MUST KNOW” TERMS
WHAT WAS .NET STANDARD?
REFERENCING AND TARGETING .NET
WHAT WAS .NET CORE?
PORTING FROM .NET FRAMEWORK TO .NET
OVERVIEW OF WEB APPLICATIONS
WHICH ASP.NET TO USE AND WHY
▸ WHAT YOU LEARNED IN THIS CHAPTER
19 Basic Cloud Programming
THE CLOUD, CLOUD COMPUTING, AND THE CLOUD OPTIMIZED STACK
CLOUD PATTERNS AND BEST PRACTICES
USING MICROSOFT AZURE C# LIBRARIES TO CREATE A STORAGE CONTAINER
CREATING AN ASP.NET CORE WEB APPLICATION THAT USES THE STORAGE CONTAINER
EXERCISES
▸ WHAT YOU LEARNED IN THIS CHAPTER
20 Basic Web API and WCF Programming
CREATING AN ASP.NET CORE WEB API
CONSUMING AN ASP.NET CORE WEB API
WHAT IS REST?
WHAT IS WCF?
WCF CONCEPTS
WCF PROGRAMMING
▸ WHAT YOU LEARNED IN THIS CHAPTER
21 Basic Desktop Programming
XAML
THE PLAYGROUND
CONTROL LAYOUT
THE GAME CLIENT
CREATING AND STYLING CONTROLS
WPF USER CONTROLS
THE MAIN WINDOW
PUTTING IT ALL TOGETHER
▸ WHAT YOU LEARNED IN THIS CHAPTER
APPENDIX: Exercise Solutions
INDEX
COPYRIGHT
ABOUT THE AUTHORS
ABOUT THE TECHNICAL EDITOR
ACKNOWLEDGMENTS
END USER LICENSE AGREEMENT
Chapter 3
TABLE 3-1: Integer Types
TABLE 3-2: Floating-Point Types
TABLE 3-3: Text and Boolean Types
TABLE 3-4: Literal Values
TABLE 3-5: Escape Sequences for String Literals
TABLE 3-6: Simple Mathematical Operators
TABLE 3-7: The String Concatenation Operator
TABLE 3-8: Increment and Decrement Operators
TABLE 3-9: Assignment Operators
TABLE 3-10: Operator Precedence
Chapter 4
TABLE 4-1: Boolean Comparison Operators
TABLE 4-2: Conditional Boolean Operators
TABLE 4-3: Boolean Assignment Operators
TABLE 4-4: Operator Precedence (Updated)
Chapter 5
TABLE 5-1: Implicit Numeric Conversions
Chapter 9
TABLE 9-1: Access Modifiers for Class Definitions
TABLE 9-2: Methods of System.Object
TABLE 9-3: Class View Icons
TABLE 9-4: Additional Class View Icons
Chapter 12
TABLE 12-1: Generic Collection Type
TABLE 12-2: Sorting with Generic Types
TABLE 12-3: Generic Type Constraints
Chapter 14
TABLE 14-1: File System Access Classes
TABLE 14-2: Static Methods of the File Class
TABLE 14-3: Static Methods of the Directory Class
TABLE 14-4: FileSystemInfo Properties
TABLE 14-5: FileInfo Properties
TABLE 14-6: Properties Unique to the DirectoryInfo Class
TABLE 14-7: Stream Classes
TABLE 14-8: FileAccess Enumeration Members
TABLE 14-9: Filemode Enumeration Members
TABLE 14-10: FileSystemWatcher Properties
Chapter 15
TABLE 15-1: Common DOM Classes
TABLE 15-2: XmlElement Properties
TABLE 15-3: Three Ways to Get the Value of a Node
TABLE 15-4: Methods for Creating Nodes
TABLE 15-5: Methods for Inserting Nodes
TABLE 15-6: Methods for Removing Nodes
TABLE 15-7: Methods for Selecting Nodes
TABLE 15-8: Common XPath Operations
Chapter 16
TABLE 16-1: Aggregate Operators for Numeric Results
Chapter 18
TABLE 18-1: Cross-Platform Key Terms
TABLE 18-2: Summary of .NET Standard Supported Version
TABLE 18-3: .NET Core Performance Improvements versus .NET Framework
TABLE 18-4: Examples of ASP.NET Server Controls
TABLE 18-5: Examples of ASP.NET Validation Controls
TABLE 18-6: ASP.NET Web Forms State Management Techniques
TABLE 18-7: Differences between Projects and Web Sites
TABLE 18-8: Baseline ASP.NET Core on Kestrel performance
TABLE 18-9: Examples of ASP.NET Core Validation Attributes
TABLE 18-10: ASP.NET Core State Management Techniques
Chapter 20
TABLE 20-1: Binding Types
TABLE 20-2: NET Default Bindings
TABLE 20-3: DataContractAttribute Properties
TABLE 20-4: DataMemberAttribute Properties
TABLE 20-5: ServiceContractAttribute Properties
TABLE 20-6: OperationContractAttribute Properties
Chapter 21
TABLE 21-1: Common Control Events
TABLE 21-2: Common Layout Panels
TABLE 21-3: Image Control Properties
TABLE 21-4: TextBox Properties
TABLE 21-5: CheckBox Properties
TABLE 21-6: RadioButton Properties
TABLE 21-7: IsReadOnly and IsEditable Combinations
TABLE 21-8: Other ComboBox Properties
TABLE 21-9: Interesting ListBox Properties
TABLE 21-10: The Name Property
TABLE 21-11: The Register( ) Method's Parameters
TABLE 21-12: Overloads for the FrameworkPropertyMetadata Constructor
TABLE 21-13: Displaying MenuItem Properties
TABLE 21-14: Property and Field Names
TABLE 21-15: Cards in Hand Dependency Properties
TABLE 21-16: Game Decks Dependency Properties
Chapter 1
FIGURE 1-1
FIGURE 1-2
FIGURE 1-3
FIGURE 1-4
Chapter 2
FIGURE 2-1
FIGURE 2-2
FIGURE 2-3
FIGURE 2-4
FIGURE 2-5
FIGURE 2-6
FIGURE 2-7
FIGURE 2-8
FIGURE 2-9
FIGURE 2-10
FIGURE 2-11
FIGURE 2-12
FIGURE 2-13
FIGURE 2-14
Chapter 3
FIGURE 3-1
FIGURE 3-2
FIGURE 3-3
FIGURE 3-4
Chapter 4
FIGURE 4-1
FIGURE 4-2
FIGURE 4-3
FIGURE 4-4
FIGURE 4-5
FIGURE 4-6
FIGURE 4-7
Chapter 5
FIGURE 5-1
FIGURE 5-2
FIGURE 5-3
FIGURE 5-4
FIGURE 5-5
FIGURE 5-6
FIGURE 5-7
FIGURE 5-8
FIGURE 5-9
FIGURE 5-10
FIGURE 5-11
FIGURE 5-12
FIGURE 5-13
FIGURE 5-14
FIGURE 5-15
Chapter 6
FIGURE 6-1
FIGURE 6-2
FIGURE 6-3
FIGURE 6-4
FIGURE 6-5
FIGURE 6-6
FIGURE 6-7
FIGURE 6-8
FIGURE 6-9
FIGURE 6-10
FIGURE 6-11
FIGURE 6-12
Chapter 7
FIGURE 7-1
FIGURE 7-2
FIGURE 7-3
FIGURE 7-4
FIGURE 7-5
FIGURE 7-6
FIGURE 7-7
FIGURE 7-8
FIGURE 7-9
FIGURE 7-10
FIGURE 7-11
FIGURE 7-12
FIGURE 7-13
FIGURE 7-14
FIGURE 7-15
FIGURE 7-16
FIGURE 7-17
FIGURE 7-18
FIGURE 7-19
FIGURE 7-20
Chapter 8
FIGURE 8-1
FIGURE 8-2
FIGURE 8-3
FIGURE 8-4
FIGURE 8-5
FIGURE 8-6
FIGURE 8-7
FIGURE 8-8
FIGURE 8-9
FIGURE 8-10
FIGURE 8-11
FIGURE 8-12
FIGURE 8-13
FIGURE 8-14
FIGURE 8-15
Chapter 9
FIGURE 9-1
FIGURE 9-2
FIGURE 9-3
FIGURE 9-4
FIGURE 9-5
FIGURE 9-6
FIGURE 9-7
FIGURE 9-8
FIGURE 9-9
FIGURE 9-10
FIGURE 9-11
FIGURE 9-12
FIGURE 9-13
FIGURE 9-14
Chapter 10
FIGURE 10-1
FIGURE 10-2
FIGURE 10-3
FIGURE 10-4
FIGURE 10-5
FIGURE 10-6
FIGURE 10-7
FIGURE 10-8
FIGURE 10-9
FIGURE 10-10
FIGURE 10-11
FIGURE 10-12
FIGURE 10-13
FIGURE 10-14
Chapter 11
FIGURE 11-1
FIGURE 11-2
FIGURE 11-3
FIGURE 11-4
FIGURE 11-5
FIGURE 11-6
FIGURE 11-7
FIGURE 11-8
Chapter 12
FIGURE 12-1
FIGURE 12-2
FIGURE 12-3
FIGURE 12-4
FIGURE 12-5
Chapter 13
FIGURE 13-1
FIGURE 13-2
FIGURE 13-3
FIGURE 13-4
FIGURE 13-5
FIGURE 13-6
FIGURE 13-7
FIGURE 13-8
FIGURE 13-9
FIGURE 13-10
FIGURE 13-11
FIGURE 13-12
FIGURE 13-13
FIGURE 13-14
FIGURE 13-15
FIGURE 13-16
FIGURE 13-17
FIGURE 13-18
FIGURE 13-19
FIGURE 13-20
FIGURE 13-21
Chapter 14
FIGURE 14-1
FIGURE 14-2
FIGURE 14-3
FIGURE 14-4
FIGURE 14-5
FIGURE 14-6
FIGURE 14-7
FIGURE 14-8
Chapter 15
FIGURE 15-1
FIGURE 15-2
FIGURE 15-3
FIGURE 15-4
FIGURE 15-5
FIGURE 15-6
FIGURE 15-7
Chapter 17
FIGURE 17-1
FIGURE 17-2
FIGURE 17-3
FIGURE 17-4
FIGURE 17-5
FIGURE 17-6
FIGURE 17-7
FIGURE 17-8
FIGURE 17-9
FIGURE 17-10
FIGURE 17-11
FIGURE 17-12
FIGURE 17-13
FIGURE 17-14
FIGURE 17-15
FIGURE 17-16
FIGURE 17-17
FIGURE 17-18
FIGURE 17-19
Chapter 18
FIGURE 18-1
FIGURE 18-2
FIGURE 18-3
FIGURE 18-4
FIGURE 18-5
FIGURE 18-6
FIGURE 18-7
FIGURE 18-8
FIGURE 18-9
FIGURE 18-10
FIGURE 18-11
FIGURE 18-12
FIGURE 18-13
FIGURE 18-14
FIGURE 18-15
FIGURE 18-16
Chapter 19
FIGURE 19-1
FIGURE 19-2
FIGURE 19-3
FIGURE 19-4
FIGURE 19-5
FIGURE 19-6
FIGURE 19-7
FIGURE 19-8
FIGURE 19-9
FIGURE 19-10
FIGURE 19-11
FIGURE 19-12
FIGURE 19-13
FIGURE 19-14
Chapter 20
FIGURE 20-1
FIGURE 20-2
FIGURE 20-3
FIGURE 20-4
FIGURE 20-5
FIGURE 20-6
FIGURE 20-7
FIGURE 20-8
FIGURE 20-9
FIGURE 20-10
FIGURE 20-11
FIGURE 20-12
FIGURE 20-13
FIGURE 20-14
FIGURE 20-15
FIGURE 20-16
FIGURE 20-17
FIGURE 20-18
Chapter 21
FIGURE 21-1
FIGURE 21-2
FIGURE 21-3
FIGURE 21-4
FIGURE 21-5
FIGURE 21-6
FIGURE 21-7
FIGURE 21-8
FIGURE 21-9
FIGURE 21-10
FIGURE 21-11
FIGURE 21-12
FIGURE 21-13
FIGURE 21-14
FIGURE 21-15
FIGURE 21-16
FIGURE 21-17
FIGURE 21-18
Cover
Table of Contents
Title Page
Copyright
About the Authors
About the Technical Editor
Acknowledgments
Introduction
Begin Reading
Appendix: Exercise Solutions
Index
End User License Agreement
v
xxvii
xxviii
xxix
xxx
xxxi
xxxii
xxxiii
1
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
48
49
50
51
52
53
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
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
154
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
186
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
228
229
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
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
286
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
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
421
423
424
425
426
427
428
429
430
431
432
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
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
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
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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
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
706
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
794
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
vi
vii
ix
xi
826
Benjamin Perkins
Jon D. Reid
THE C# LANGUAGE WAS UNVEILED TO THE WORLD when Microsoft announced the first version of its .NET Framework in 2002. Since then, its popularity has rocketed, and it has arguably become the language of choice for desktop, web, cloud, and cross‐platform developers who use .NET. Part of the appeal of C# comes from its clear syntax, which derives from C/C++ but simplifies some things that have previously discouraged some programmers. Despite this simplification, C# has retained the power of C++, and there is no reason now not to move into C#. The language is not difficult, and it is a great one with which to learn elementary programming techniques. This ease of learning combined with the capabilities of the .NET Framework make C# an excellent way to start your programming career.
The latest release of C# is C# 9 (included with.NET 5.0 and .NET Framework 4.8), which builds on the existing successes and adds even more attractive features. The latest releases of both Visual Studio and Visual Studio Code line of development tools also bring many tweaks and improvements to make your life easier and to dramatically increase your productivity.
This book is intended to teach you about all aspects of C# programming, including the language itself, desktop, cloud, and cross‐platform programming, making use of data sources, and some new and advanced techniques. You will also learn about the capabilities of Visual Studio and all the ways that this product can aid your application development.
The book is written in a friendly, mentor‐style fashion, with each chapter building on previous ones, and every effort is made to ease you into advanced techniques painlessly. At no point will technical terms appear from nowhere to discourage you from continuing; every concept is introduced and discussed as required. Technical jargon is kept to a minimum, but where it is necessary, it, too, is properly defined and laid out in context.
The authors of this book are both experts in their field and are enthusiastic in their passion for the C# language and .NET. Nowhere will you find two people better qualified to take you under their collective wing and nurture your understanding of C# from first principles to advanced techniques. Along with the fundamental knowledge it provides, this book is packed full of helpful hints, tips, exercises, and full‐fledged example code (available for download on this book's web page at www.wiley.com and at github.com/benperk/BeginningCSharpAndDotNET) that you will find yourself returning to repeatedly as your career progresses.
We pass this knowledge on without begrudging it and hope that you will be able to use it to become the best programmer you can be. Good luck, and all the best!
This book is for everyone who wants to learn how to program in C# using .NET. It is for absolute beginners who want to give programming a try by learning a clean, modern, elegant programming language. But it is also for people familiar with other programming languages who want to explore the .NET platform, as well as for existing .NET developers who want to give Microsoft's .NET flagship language a try.
The early chapters cover the language itself, assuming no prior programming experience. If you have programmed in other languages before, much of the material in these chapters will be familiar. Many aspects of C# syntax are shared by other languages, and many structures are common to practically all programming languages (such as looping and branching structures). However, even if you are an experienced programmer, you will benefit from looking through these chapters to learn the specifics of how these techniques apply to C#.
If you are new to programming, you should start from the beginning, where you will learn basic programming concepts and become acquainted with both C# and the .NET platform that underpins it. If you are new to .NET but know how to program, you should read Chapter 1 and then skim through the next few chapters before continuing with the application of the C# language. If you know how to program but have not encountered an object‐oriented programming language before, you should read the chapters from Chapter 8 onward.
Alternatively, if you already know the C# language, you might want to concentrate on the chapters dealing with the most recent .NET and C# language developments, specifically the chapters on collections, generics, and C# language enhancements (Chapters 11 and 12).
The chapters in this book have been written with a dual purpose in mind: They can be read sequentially to provide a complete tutorial in the C# language, and they can be dipped into as required for reference material.
In addition to the core material, starting with Chapter 3 most chapters also include a selection of exercises at the end, which you can work through to ensure that you have understood the material. The exercises range from simple multiple choice or true/false questions to more complex exercises that require you to modify or build applications. The answers to all the exercises are provided in the Appendix. You can also find these exercises as part of the wiley.com code downloads on this book's page at www.wiley.com.
Every chapter receives an overhaul with every new release of C# and .NET, the less relevant material is removed, and new material added. All the code has been tested against the latest version of the development tools used, and all the screenshots have been retaken in the most current version of the Windows OS to provide the most current windows and dialog boxes. New highlights of this edition include the following:
Additional and improved code examples for you to try out
Examples of programming ASP.NET Core for running cross‐platform
Examples of programming cloud applications, using Azure SDK to create and access cloud resources
This book is divided into four sections:
Introduction
—Purpose and general outline of the book's contents
The C# Language
—Covers all aspects of the C# language, from the fundamentals to object‐oriented techniques
Data Access
—How to use data in your applications, including data stored in files on your hard disk, data stored in XML format, and data in databases
Additional Techniques
—An examination of some extra ways to use C# and .NET, including cloud and cross‐platform development, ASP.NET Web API, Windows Presentation Foundation (WPF), Windows Communication Foundation (WCF), and Universal Windows Applications
The following sections describe the chapters in the three major parts of this book.
Chapter 1 introduces you to C# and how it fits into the .NET landscape. You will learn the fundamentals of programming in this environment and how Visual Studio (VS) fits in.
Chapter 2 starts you off with writing C# applications. You will look at the syntax of C# and put the language to use with sample command‐line and Windows applications. These examples demonstrate just how quick and easy it can be to get up and running, and along the way you will be introduced to the Visual Studio development environment and the basic windows and tools that you'll be using throughout the book.
Next, you will learn more about the basics of the C# language. You will learn what variables are and how to manipulate them in Chapter 3. You will enhance the structure of your applications with flow control (looping and branching) in Chapter 4, and you will see some more advanced variable types such as arrays in Chapter 5. In Chapter 6 you will start to encapsulate your code in the form of functions, which makes it much easier to perform repetitive operations and makes your code much more readable.
By the beginning of Chapter 7 you will have a handle on the fundamentals of the C# language, and you will focus on debugging your applications. This involves looking at outputting trace information as your applications are executed, and at how Visual Studio can be used to trap errors and lead you to solutions for them with its powerful debugging environment.
From Chapter 8 onward you will learn about object‐oriented programming (OOP), starting with a look at what this term means and an answer to the eternal question, “What is an object?” OOP can seem quite difficult at first. The whole of Chapter 8 is devoted to demystifying OOP and explaining what makes it so great, and you will not actually deal with much C# code until the very end of the chapter.
Everything changes in Chapter 9, when you put theory into practice and start using OOP in your C# applications. This is where the true power of C# lies. You will start by looking at how to define classes and interfaces, and then move on to class members (including fields, properties, and methods) in Chapter 10. At the end of that chapter, you will start to assemble a card game application, which is developed over several chapters and will help to illustrate OOP.
Once you have learned how OOP works in C#, Chapter 11 moves on to look at common OOP scenarios, including dealing with collections of objects, and comparing and converting objects. Chapter 12 looks at a useful feature of C# that was introduced in .NET 2.0: generics, which enable you to create very flexible classes. Next, Chapter 13 continues the discussion of the C# language and OOP with some additional techniques, notably events, which become important in, for example, Windows programming. Chapter 13 wraps up the fundamentals by focusing on C# language features that were introduced in some of the more recent versions of C#.
Chapter 14 looks at how your applications can save and retrieve data to disk, both as simple text files and as more complex representations of data. You will also learn how to compress data and how to monitor and act on file system changes.
In Chapter 15 you will learn about the de facto standard for data exchange—namely XML—and a rapidly emerging format called JSON. By this point in the book, you will have touched on XML several times in preceding chapters, but this chapter lays out the ground rules and shows you what all the excitement is about.
The remainder of this part looks at LINQ, which is a query language built into .NET. You start in Chapter 16 with a general introduction to LINQ, and then you will use LINQ to access a database and other data in Chapter 17.
Chapter 18 introduces .NET Standard and .NET Core, which are tools used for targeting any application type—for example, Windows Presentation Foundation (WPF), Windows, and ASP.NET. An emerging application is one that can run cross‐platform such as on Linux or macOS. The chapter provides instructions for installing .NET and creating and implementing a .NET Standard library. Additionally, descriptions of ASP.NET and its many different types (e.g., ASP.NET Webforms, ASP.NET MVC, and ASP.NET Core) are covered.
Chapter 19 starts by describing what cloud programming is and discusses the cloud‐optimized stack. The cloud environment is not identical to the way programs have been traditionally coded, so a few cloud programming patterns are discussed and defined. To complete this chapter, you require an Azure trail account, which is free to create and comes with some credits so that you can create and test out an App Service Web App. Then, using the Azure SDK with C#, you create and access a storage account from an ASP.NET web application.
In Chapter 20, you learn how to create an ASP.NET Web API and consume it using a Blazor WebAssembly App. Then this chapter provides an introduction to Windows Communication Foundation (WCF), which provides you with the tools you need for enterprise‐level programmatic access to information and capabilities across local networks and the internet. You will see how you can use WCF to expose complex data and functionality to web and desktop applications in a platform‐independent way.
Chapter 21 starts by introducing you to what is meant by Windows programming and looks at how this is achieved in Visual Studio. It focuses on WPF (Windows Presentation Foundation) as a tool that enables you to build desktop applications in a graphical way and assemble advanced applications with a minimum of effort and time. You will start with the basics of WPF programming and build up your knowledge to more advanced concepts.
The code and descriptions of C# and .NET in this book apply to C# 9 and .NET 4.8. You do not need anything other than .NET to understand this aspect of the book, but many of the examples require a development tool. This book uses the most current version of Visual Studio Community 2019 as its primary development tool. Use Visual Studio Community 2019 to create Windows, cloud, and cross‐platform applications as well as SQL Server Express for applications that access databases.
The source code for the samples is available for download from this book's page on www.wiley.com and at github.com/benperk/BeginningCSharpAndDotNET.
To help you get the most from the text and keep track of what is happening, we've used a number of conventions throughout the book.
The Try It Out is an exercise you should work through, following the text in the book.
These exercises usually consist of a set of steps.
Each step has a number.
Follow the steps through to the end.
After each Try It Out, the code you've typed will be explained in detail.
WARNING Warnings hold important, not‐to‐be‐forgotten information that is directly relevant to the surrounding text.
NOTE Shaded boxes like this hold notes, tips, hints, tricks, or asides to the current discussion.
As for styles in the text:
We
italicize
new terms and important words when we introduce them.
We show keyboard strokes like this: Ctrl+A.
We show filenames, URLs, and code within the text like so:
persistence.properties
We present code in two different ways:
We use a monofont type with no highlighting for most code examples.
We use bold to emphasize code that is particularly important in the present
context or to show changes from a previous code snippet.
As you work through the examples in this book, you may choose either to type in all the code manually or to use the source code files that accompany the book. All the source code used in this book is available for download on this book's page at www.wiley.com and at github.com/benperk/BeginningCSharpAndDotNET.
Most of the code on www.wiley.com is compressed in a .ZIP, .RAR archive, or similar archive format appropriate to the platform. Once you download the code, just decompress it with an appropriate compression tool.
NOTE Because many books have similar titles, you may find it easiest to search by ISBN; this book's ISBN is 978‐1‐119‐79578‐0.
We make every effort to ensure that there are no errors in the text or in the code. However, no one is perfect, and mistakes do occur. If you find an error in one of our books, like a spelling mistake or faulty piece of code, we would be very grateful for your feedback. By sending in errata, you may save another reader hours of frustration, and at the same time, you will be helping us provide even higher quality information.
To find the errata page for this book, go to this book's page at www.wiley.com and click the Errata link. On this page you can view all errata that have been submitted for this book.
CHAPTER 1
:
Introducing C#
CHAPTER 2
:
Writing a C# Program
CHAPTER 3
:
Variables and Expressions
CHAPTER 4
:
Flow Control
CHAPTER 5
:
More about Variables
CHAPTER 6
:
Functions
CHAPTER 7
:
Debugging and Error Handling
CHAPTER 8
:
Introduction to Object‐Oriented Programming
CHAPTER 9
:
Defining Classes
CHAPTER 10
:
Defining Class Members
CHAPTER 11
:
Collections, Comparisons, and Conversions
CHAPTER 12
:
Generics
CHAPTER 13
:
Additional C# Techniques
WHAT YOU WILL LEARN IN THIS CHAPTER
What .NET is
What C# is
Explore Visual Studio
Welcome to the first chapter of the first part of this book. Part I provides you with the basic knowledge you need to get up and running with C#. Specifically, this chapter provides an overview of .NET and C#, including what these technologies are, the motivation for using them, and how they relate to each other.
This chapter begins with a general discussion of .NET, which contains many concepts that are tricky to come to grips with initially. This means that the discussion, of necessity, covers many concepts in a short amount of space. However, a quick look at the basics is essential to understand how to program in C#. Later in the book, you revisit many of the topics covered here, exploring them in more detail.
After this general .NET introduction, the chapter provides a basic description of C# itself, including its origins and similarities to C++. Finally, you look at the primary tool used throughout this book: Visual Studio (VS). Visual Studio is an Integrated Development Environment (IDE) that Microsoft has produced since the late 1990s and gets updated regularly with new features. Visual Studio includes all sorts of capabilities including full support for desktop, cloud, web, mobile, database, machine learning, AI, and cross-platform programming that you will learn about throughout this book.
.NET is a revolutionary software framework created by Microsoft for developing computer programs. To begin with, note that .NET provides more than the means for creating programs that target the Windows operating system. .NET is fully open source and fully supports running cross platform. Cross platform means that the code you write using .NET will run on Linux and MacOS operating systems as well. The source code for .NET is open source and you can find it at github.com/dotnet/core.
The .NET software framework is made of prewritten computer code, which provides simple access to basic computing resources like the hard drive and computer memory. One aspect of this framework is referred to as the Base Class Library (BCL), which contains the System class. You will become very familiar with it as you progress through this book. Taking a deeper look into the source code inside the System class, you will find that it includes the definitions of data types like strings, integers, Boolean, and characters . If you need one of these data types in your program to store information, you can use the already written .NET code to achieve that. If such code did not already exist, you would need to use low-level programming languages like assembly or machine code to allocate and manage the required memory yourself. The basic types found in the System class also facilitate interoperability between .NET programming languages, a concept referred to as the Common Type System (CTS). Interoperability means that a string in C# has the same attributes and behaviors as a string in Visual Basic or F#. Besides supplying this source code library, .NET also includes the Common Language Runtime (CLR), which is responsible for the execution of all applications developed using the .NET library; more on that later.
In addition to the System class, .NET contains many, many other classes, often called modules. Some would say it is a gigantic library of object-oriented programming (OOP) code categorized into different modules—you use portions of it depending on the results you want to achieve. For example, System.IO and System.Text are the classes you would use to read and write to files located on a computer hard drive. A programmer can manipulate the contents of a file simply by using the code that already exists in the System.IO class without needing to manage handles or load the file from the hard drive into memory. There exist many classes in .NET that help programmers write programs at a fast pace, because all of the low-level code required to achieve their tasks has already been written. The programmer only needs the knowledge of which classes they require to achieve the program objectives.
Not only does .NET speed up application development, but it also can be utilized by numerous other programming languages, not just C# (which is the subject of this book). Programs written in C++, F#, Visual Basic, and even older languages such as COBOL can use the classes that exist in .NET. These languages have access to the code in the .NET library, but the code written in one programming language can communicate with code from another. For example, a program written in C# can make use of code written in Visual Basic or F# and vice versa. All of these examples are what makes .NET such an attractive prospect for building customized software.
When the .NET Framework was originally created, it targeted the Windows operating system platform. Through the years, the .NET Framework code was forked to support numerous other platforms like IoT devices, desktops, mobile devices, and other operating systems. You may recognize some of the branches going by the names of .NET Compact Framework, .NET Portable, or .NET Micro Framework. Each of these forks contained its own, slightly modified BCL. Take note that a BCL is more than just strings, Booleans, and integers . It includes capabilities like file access, string manipulation, managing streams, storing data in collections, security attributes, and many others.
Having even a slightly different BCL required a programmer to learn, develop, and manage the subtle difference between the BCLs for each .NET fork. Each fork of the .NET Framework that targeted desktops, the Internet, or mobile platforms could have significant implementation differences, even though each program used .NET. It was (and still is) very common for a company to have desktop, website, and phone applications that ran the same program logic but did so on those different platforms. In that scenario, using .NET required a version of the company's application for each platform. That was not efficient. This is the problem that the .NET Standard solved. The .NET Standard provided a place for programmers to create application logic that could be used across any of the .NET Framework forks. The .NET Standard made the different platforms, like desktop, mobile, and web, BCL agnostic by decoupling a company's program logic from platform-specific dependencies.
.NET Core was the open source, cross-platform version of the .NET library. This fork of the code could be used to create programs that targeted numerous different platforms and operating systems like Linux, MacOS, and of course Windows. It was also the fork that would eventually become the one and only maintained branch of the .NET source code library. As of 2020, knowing about the .NET Framework, .NET Standard, and .NET Core is no longer as relevant as it once was. These three branches of .NET must be mentioned here because you will still likely see them, read about them, and be confronted with them for some years to come. It is important that you know what they are and their purpose, in case you need to work on a project that implements them. As of 2020, there is a new version of .NET simply named “.NET.” .NET is fully open source, is fully cross platform, and can be used on many platforms without having to support multiple versions, forks, and branches of your program.
Creating a computer program with .NET means writing code that uses existing code found within the .NET library. In this book you use Visual Studio for developing your programs. Visual Studio is a powerful, integrated development environment that supports C# (as well as C++, Visual Basic, F#, and some others). The advantage of this environment is the ease with which .NET features can be integrated into your code. The code that you create will be entirely C# but use .NET throughout, and also some additional tools in Visual Studio, where necessary. For C# code to execute, it must be converted into a language that the target operating system understands, known as native code. This conversion is called compiling, an act that is performed by a compiler, which is a two-stage process.
When you compile code that uses .NET, you don't immediately create operating system–specific native code. Instead, you compile your code into Common Intermediate Language (CIL) code. This code isn't specific to any operating system (OS) and isn't specific to C#. Other .NET languages—Visual Basic .NET or F#, for example—also compile to this language as a first stage. This compilation step is carried out by Visual Studio when you develop C# applications.
Obviously, more work is necessary to execute an application. That is the job of a just-in-time (JIT) compiler, which compiles CIL into native code that is specific to the OS and machine architecture being targeted. Only at this point can the OS execute the application. The just-in-time part of the name reflects the fact that CIL code is compiled only when it is needed. This compilation can happen on the fly while your application is running, although luckily this isn't something that you normally need to worry about as a developer. Unless you are writing extremely advanced code where performance is critical, it's enough to know that this compilation process will churn along merrily in the background, without interfering.
In the past, it was often necessary to compile your code into several applications, each of which targeted a specific operating system and CPU architecture. Typically, this was a form of optimization (to get code to run faster on an AMD chipset, for example), but at times, it was critical (for applications to work in both Win9x and WinNT/2000 environments, for example). This is now unnecessary because JIT compilers (as their name suggests) use CIL code, which is independent of the machine, operating system, and CPU. Several JIT compilers exist, each targeting a different architecture, and the CLR uses the appropriate one to create the native code required.
The beauty of all this is that it requires a lot less work on your part—in fact, you can forget about system-dependent details and concentrate on the more interesting functionality of your code.
NOTE As you learn about .NET, you might come across references to Microsoft Intermediate Language (MSIL). MSIL was the original name for CIL, and many developers still use this terminology today. See en.wikipedia.org/wiki/Common_Intermediate_Language for more information about CIL (also known as Intermediate Language [IL]).
When you compile an application, the CIL code is stored in an assembly. Assemblies include both executable application files that you can run directly from Windows without the need for any other programs (these have an .exe file extension) and libraries (which have a .dll extension) for use by other applications.
In addition to containing CIL, assemblies also include meta information (that is, information about the information contained in the assembly, also known as metadata) and optional resources (additional data used by the CIL, such as sound files and pictures). The meta information enables assemblies to be fully self-descriptive. You need no other information to use an assembly, meaning you avoid situations such as failing to add required data to the system registry and so on, which was often a problem when developing with other platforms.
This means that deploying applications is often as simple as copying the files into a directory on a remote computer. Because no additional information is required on the target systems, you can just run an executable file from this directory and, assuming the CLR is installed for .NET targeted applications, you're good to go. Depending on the deployment scenario, the modules required to run the program are included in the deployment package which means no additional configurations.
From a .NET perspective, you won't necessarily want to include everything required to run an application in a single directory. You might write some code that performs tasks required by multiple applications. In situations like these, it is often useful to place the reusable code in a place accessible to all applications. In .NET, this place is the global assembly cache (GAC). Placing code in the GAC is simple—you just place the assembly containing the code in the directory containing this cache.
The role of the CLR doesn't end after you have compiled your code to CIL and a JIT compiler has compiled that to native code. Code written using .NET is managed when it is executed (a stage usually referred to as runtime). This means that the CLR looks after your applications by managing memory, handling security, allowing cross-language debugging, and so on. By contrast, applications that do not run under the control of the CLR are said to be unmanaged, and certain languages such as C++ can be used to write such applications, which, for example, access low-level functions of the operating system. However, in C#, you can write only code that runs in a managed environment. You will make use of the managed features of the CLR and allow .NET itself to handle any interaction with the operating system.
One of the most important features of managed code is the concept of garbage collection. This is the .NET method of making sure that the memory used by an application is freed up completely when the application is no longer using it. Prior to .NET, this was mostly the responsibility of programmers, and a few simple errors in code could result in large blocks of memory mysteriously disappearing as a result of being allocated to the wrong place in memory. That usually meant a progressive slowdown of your computer, followed by a system crash.
.NET garbage collection works by periodically inspecting the memory of your computer and removing anything from it that is no longer needed. There is no set time frame for this; it might happen thousands of times a second, once every few seconds, or whenever, but you can rest assured that it will happen.
There are some implications for programmers here. Because this work is done for you at an unpredictable time, applications have to be designed with this in mind. Code that requires a lot of memory to run should tidy itself up, rather than wait for garbage collection to happen, but that isn't as tricky as it sounds.
Before moving on, let's summarize the steps required to create a .NET application as discussed previously:
Application code is written using a .NET-compatible language such as C# (see
Figure 1-1
).
FIGURE 1-1
That code is compiled into CIL, which is stored in an assembly (see
Figure 1-2
).
FIGURE 1-2
When this code is executed (either in its own right if it is an executable or when it is used from other code), it must first be compiled into native code using a JIT compiler (see
Figure 1-3
).
FIGURE 1-3
The native code is executed in the context of the managed CLR, along with any other running applications or processes, as shown in
Figure 1-4
.
FIGURE 1-4
Note one additional point concerning this process. The C# code that compiles into CIL in step 2 need not be contained in a single file. It is possible to split application code across multiple source-code files, which are then compiled together into a single assembly. This extremely useful process is known as linking. This is required because it is far easier to work with several smaller files than one enormous one. You can separate logically related code into an individual file so that it can be worked on independently and then practically forgotten about when completed. This also makes it easy to locate specific pieces of code when you need them and enables teams of developers to divide the programming burden into manageable chunks. This allows individuals to “check out” pieces of code to work on without risking damage to otherwise satisfactory sections or sections other people are working on.
C#, as mentioned earlier, is one of the languages you can use to create applications that will run in the .NET CLR. It is an evolution of the C and C++ languages and has been created by Microsoft specifically to work with the .NET platform. The C# language has been designed to incorporate many of the best features from other languages while clearing up their problems.
Developing applications using C# is simpler than using C++ because the language syntax is simpler. Still, C# is a powerful language, and there is little you might want to do in C++ that you can't do in C#. Having said that, those features of C# that parallel the more advanced features of C++, such as directly accessing and manipulating system memory, can be carried out only by using code marked as unsafe. This advanced programmatic technique is potentially dangerous (hence its name) because it is possible to overwrite system-critical blocks of memory with potentially catastrophic results. For this reason, and others, this book does not cover that topic.
At times, C# code is slightly more verbose than C++. This is a consequence of C# being a typesafe language (unlike C++). In layperson's terms, this means that once some data has been assigned to a type, it cannot subsequently transform itself into another unrelated type. Consequently, strict rules must be adhered to when converting between types, which means you will often need to write more code to carry out the same task in C# than you might write in C++. However, there are benefits to this—the code is more robust, debugging is simpler, and .NET can always track the type of a piece of data at any time. In C#, you therefore might not be able to do things such as “take the region of memory 4 bytes into this data and 10 bytes long and interpret it as X,” but that's not necessarily a bad thing.
C# is just one of the languages available for .NET development, but it is certainly the best. It has the advantage of being the only language designed from the ground up for .NET and is the principal language used in versions of .NET that are ported to other operating systems. To keep languages such as the .NET version of Visual Basic as similar as possible to their predecessors yet compliant with the CLR, certain features of the .NET code library are not fully supported, or at least require unusual syntax.
By contrast, C# can make use of every feature the .NET code library has to offer. Also, each new version of .NET has included additions to the C# language, partly in response to requests from developers, making it even more powerful.
.NET has no restrictions on the types of applications that are possible. C# uses the framework and therefore has no restrictions on possible applications. However, here are a few of the more common application types:
Desktop applications
—Applications, such as Microsoft Office, that have a familiar Windows look and feel about them. This is made simple by using the Windows Presentation Foundation (WPF) module of .NET, which is a library of
controls
(such as buttons, toolbars, menus, and so on) that you can use to build a Windows user interface (UI).
Cloud/web applications
—.NET includes a powerful system named ASP.NET Core, for generating web content dynamically, enabling personalization, security, and much more. Additionally, these applications can be hosted and accessed in the cloud, for example on the Microsoft Azure platform.
Mobile applications
—Using both C# and Xamarin mobile UI framework you can target mobile applications that target the Android operating system.
Web APIs
—An ideal framework for building RESTful HTTP services that support a broad variety of clients, including mobile devices and browsers. These are also referred to as REST APIs.
WCF services
—A way to create versatile distributed applications. With WCF, you can exchange virtually any data over local networks or the Internet, using the same simple syntax regardless of the language used to create a service or the system on which it resides. This is an older technology that would require an older version of the .NET Framework to create.
Any of these types of applications might also require some form of database access, which can be achieved using the ADO.NET (Active Data Objects .NET) feature set of .NET, through the Entity Framework, or through the LINQ (Language Integrated Query) capabilities of C#. Many other resource assemblies can be utilized that are helpful with creating networking components, outputting graphics, performing complex mathematical tasks, and so on.
Part I