32,99 €
Sharpen your knowledge of C# C# know-how is a must if you want to be a professional Microsoft developer. It's also good to know a little C# if you're building tools for the web, mobile apps, or other development tasks. C# 7.0 All-in-One For Dummies offers a deep dive into C# for coders still learning the nuances of the valuable programming language. Pop it open to get an intro into coding with C#, how to design secure apps and databases, and even pointers on building web and mobile apps with C#. C# remains one of the most in-demand programming language skills. The language regularly ranks in the top five among "most in-demand" languages, typically along with Java/JavaScript, C++, and Python. A December 2016 ZDNet article noted 'If your employer is a Microsoft developer, you better know C#." Lucky for you, this approachable, all-in-one guide is here to help you do just that--without ever breaking a sweat! Includes coverage of the latest changes to C# * Shows you exactly what the language can (and can't) do * Presents familiar tasks that you can accomplish with C# * Provides insight into developing applications that provide protection against hackers If you have a basic understanding of coding and need to learn C#--or need a reference on the language in order to launch or further your career--look no further.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 1037
Veröffentlichungsjahr: 2017
C# 7.0 All-in-One For Dummies®
Published by: John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030-5774, www.wiley.com
Copyright © 2018 by John Wiley & Sons, Inc., Hoboken, New Jersey
Media and software compilation copyright © 2018 by John Wiley & Sons, Inc. All rights reserved.
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: THE PUBLISHER AND THE AUTHOR 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 WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ.
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: 2017958295
ISBN: 978-111-9-42811-4; ISBN 978-111-9-42810-7 (ebk); ISBN ePDF 978-111-9-42812-1 (ebk)
Cover
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
Introducing the Toolbox Trick
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 the Command Line
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
Nesting Loops
Don’t goto Pieces
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
On Not Using Old-Fashioned Collections
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
Revising Generics
Chapter 9: Some Exceptional Exceptions
Using an Exceptional Error-Reporting Mechanism
Throwing Exceptions Yourself
Knowing What Exceptions Are For
Can I Get an Exceptional Example?
Assigning Multiple catch Blocks
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
Book 2: Object-Oriented C# Programming
Chapter 1: Object-Oriented Programming — What’s It All About?
Object-Oriented Concept #1: Abstraction
Object-Oriented Concept #2: Classification
Why Classify?
Object-Oriented Concept #3: Usable Interfaces
Object-Oriented Concept #4: Access Control
How C# Supports Object-Oriented Concepts
Chapter 2: Showing Some Class
Defining a Class and an Object
Accessing the Members of an Object
An Object-Based Program Example
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 3: We Have Our Methods
Defining and Using a Method
A Method Example for Your Files
Having Arguments with Methods
Returning Values after Christmas
Returning Multiple Values Using Tuples
Chapter 4: Let Me Say This about this
Passing an Object to a Method
Defining Methods
Accessing the Current Object
Using Local Functions
Chapter 5: Holding a Class Responsible
Restricting Access to Class Members
Why You Should Worry about Access Control
Defining Class Properties
Getting Your Objects Off to a Good Start — Constructors
The C#-Provided Constructor
Replacing the Default Constructor
Using Expression-Bodied Members
Chapter 6: Inheritance: Is That All I Get?
Class Inheritance
Why You Need Inheritance
Inheriting from a BankAccount Class (a More Complex Example)
IS_A versus HAS_A — I’m So Confused_A
When to IS_A and When to HAS_A
Other Features That Support Inheritance
The object Class
Inheritance and the Constructor
The Updated BankAccount Class
Chapter 7: Poly-what-ism?
Overloading an Inherited Method
Polymorphism
The Class Business Card: ToString()
C# During Its Abstract Period
Sealing a Class
Chapter 8: 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 9: 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 10: Can I Use Your Namespace in the Library?
Dividing a Single Program into Multiple Source Files
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
Chapter 11: Improving Productivity with Named and Optional Parameters
Exploring Optional Parameters
Looking at Named Parameters
Dealing with Overload Resolution
Using Alternative Methods to Return Values
Chapter 12: Interacting with Structures
Comparing Structures to Classes
Creating Structures
Using Structures as Records
Book 3: Designing for C#
Chapter 1: Writing Secure Code
Designing Secure Software
Building Secure Windows Applications
Building Secure Web Forms 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
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
Using Snippets
Hacking the Project Types
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
Book 6: Web Development with ASP.NET
Chapter 1: Looking at How ASP.NET Works with C#
Breaking Down Web Applications
Questioning the Client
Dealing with Web Servers
Chapter 2: Building Web Applications
Working in Visual Studio
Developing with Style
Chapter 3: Controlling Your Development Experience
Showing Stuff to the User
Getting Some Input from the User
Data Binding
Styling Your Controls
Making Sure the Site Is Accessible
Constructing User Controls
Chapter 4: Leveraging the .NET Framework
Surfing Web Streams
Securing ASP.NET
Managing Files
Baking Cookies
Tracing with TraceContext
Navigating with Site Maps
About the Author
Advertisement Page
Connect with Dummies
End User License Agreement
Cover
Table of Contents
Begin Reading
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
48
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
80
81
82
83
84
85
86
87
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
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
223
224
225
226
227
228
229
230
231
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
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
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
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
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
432
433
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
459
460
461
462
463
464
465
466
467
469
470
471
472
473
474
475
476
477
478
479
480
481
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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
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
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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
641
642
643
644
645
646
647
648
649
650
651
652
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
706
707
708
709
710
711
712
713
714
715
716
717
718
719
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
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
831
833
835
836
C# is an amazing language! You can use this single language to do everything from desktop development to creating web applications and even web-based application programming interfaces (APIs). 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# 7.0 All-in-One For Dummies is your doorway to this new adventure in development.
So, why do you need C# 7.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 2017 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# 7.0 in the least possible time.
Even if you have past experience with C#, the new features in C# 7.0 will have you producing feature-rich applications in an even shorter time than you may have before. C# 7.0 All-in-One For Dummies introduces you to all these new features. For example, you discover the new pattern-matching techniques that C# 7.0 provides. You also discover the wonders of using tuples and local functions. Even the use of literals has improved, but you’ll have to look inside to find out how. This particular book is designed to make using C# 7.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. 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 to some degree. 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 timesaving 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. John Mueller provides online content to make this book more flexible and better able to meet your needs. Also, you can send John email. He’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# 7.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
. You can also download Online Chapters 1–7. To find the source code and online chapters, search this book’s title at
www.dummies.com
and locate the Downloads tab on the page that appears.
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.
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 2017 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 2017. To help ensure that everyone can participate, this book focuses on the features offered by Visual Studio 2017 Community Edition, which is a free download. That’s right, you can discover the wonders of C# 7.0 without paying a dime!
The more you know about C#, the further 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.
Book 1
Contents at a Glance
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
Introducing the Toolbox Trick
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 the Command Line
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
Nesting Loops
Don’t goto Pieces
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
On Not Using Old-Fashioned Collections
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
Revising Generics
Chapter 9: Some Exceptional Exceptions
Using an Exceptional Error-Reporting Mechanism
Throwing Exceptions Yourself
Knowing What Exceptions Are For
Can I Get an Exceptional Example?
Assigning Multiple catch Blocks
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
Chapter 1
IN THIS CHAPTER
Getting a quick introduction to programming
Creating a simple console application
Examining the console application
Saving code for later
This chapter explains a little bit about computers, computer languages — including the computer language C# (pronounced “see sharp”) — and Visual Studio 2017. You then create a simple program written in C#.
A computer is an amazingly fast but incredibly stupid servant. 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 at me and say something like, “Hey, my telephone lets me dial my friend by just speaking his name.” Yes, a tiny computer runs your telephone. So that computer speaks English. But that’s a computer program that understands English, not the computer itself.
The language that computers truly understand is machine language. It’s possible, but extremely difficult and error prone, for humans to write machine language.
Humans and computers have decided to meet somewhere in the middle. Programmers create programs in a language that isn't nearly as free as human speech, but it's a lot more flexible and easier to use than machine language. 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, which 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.
The C# programming language is one of those intermediate languages that programmers use 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. (Visual Basic’s newer .NET incarnation is almost on par with C# in most respects. As the flagship language of .NET, C# tends to introduce most new features first.) 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 readily create complicated display frames with drop-down lists, tabbed windows, grouped buttons, scroll bars, and background images, to name just a few.
.NET is pronounced “dot net.”
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.
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. You can find a good amount of information later in this book on how to use C# to write Windows, web, and service applications.
.NET began several years ago as Microsoft’s strategy to open the web to mere mortals like you and me. Today, it’s bigger than that, encompassing everything Microsoft does. In particular, it’s the new way to program for Windows. It also gives a C-based language, C#, the simple, visual tools that made Visual Basic so popular.
A little background helps you see the roots of C# and .NET. Internet programming was traditionally very difficult in older languages such as C and C++. Sun Microsystems responded to that problem by creating the Java programming language. To create Java, Sun took the grammar of C++, made it a lot more user friendly, and centered it around distributed development.
When programmers say “distributed,” they’re describing geographically dispersed computers running programs that talk to each other — via the Internet in many cases.
When Microsoft licensed Java some years ago, it ran into legal difficulties with Sun over changes it wanted to make to the language. As a result, Microsoft more or less gave up on Java and started looking for ways to compete with it.
Being forced out of Java was just as well because Java has a serious problem: Although Java is a capable language, you pretty much have to write your entire program in Java to get the full benefit. Microsoft had too many developers and too many millions of lines of existing source code, so Microsoft had to come up with some way to support multiple languages. Enter .NET.
.NET is a framework, in many ways similar to Java’s libraries — and the C# language is highly similar to the Java language. Just as Java is both the language itself and its extensive code library, C# is really much more than just the keywords and syntax of the C# language. It’s those things empowered by a well-organized library containing thousands of code elements that simplify doing about any kind of programming you can imagine, from web-based databases to cryptography to the humble Windows dialog box.
Microsoft would claim that .NET is much superior to Sun’s suite of web tools based on Java, but that’s not the point. Unlike Java, .NET doesn't require you to rewrite existing programs. A Visual Basic programmer can add just a few lines to make an existing program web-knowledgeable (meaning that it knows how to get data off the Internet). .NET supports all the common Microsoft languages — and hundreds of other languages written by third-party vendors. However, C# is the flagship language of the .NET fleet. C# is always the first language to access every new feature of .NET.
(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 nifty-gifty 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 .NET.
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 2017 is the ninth-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, then reviewing all of Book 4 is helpful.)
Microsoft calls its implementation of the language Visual C#. In reality, Visual C# is nothing more than the C# component of Visual Studio. C# is C#, with or without Visual Studio. Theoretically, you could write C# programs by using any text editor and a few special tools, but using Visual Studio is so much easier that you wouldn’t want to try.
Okay, that’s it. No more questions. (For now, anyway.)
Visual Studio 2017 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.
This starter program isn't even a graphical program, though. A console application is one that runs in the “console” within Windows, usually referred to as the DOS prompt or command window. If you press Ctrl+R and then type cmd, you see a command window. It’s the console where the application will run.
The following instructions are for Visual Studio. If you use anything other than Visual Studio, you have to refer to the documentation that came with your environment. Alternatively, you can just type the source code directly into your C# environment.
To start Visual Studio, press the Windows button on your keyboard and type Visual Studio. Visual Studio 2017 appears as one of the available options. You can access the example code for this chapter in the \CSAIO4D\BK01\CH01 folder in the downloadable source, as explained in the Introduction.
Complete these steps to create your C# console app:
Open Visual Studio 2017 and click the Create New Project link, shown in Figure1-1.
Visual Studio presents you with lots of icons representing the different types of applications you can create, as shown in Figure 1-2.
In this New Project window, click the Console App (.NET Framework) icon.
Make sure that you select Visual C# — and under it, Windows — in the Project Types pane; otherwise Visual Studio may create something awful like a Visual Basic or Visual C++ application. Then click the Console App (.NET Framework) icon in the Templates pane.
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 2017 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
The default name for your first application is App1, 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:\CSAIO4D\BK01\CH01
Location field to change the location of this project.
Click the OK 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-3, 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.
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.
FIGURE 1-3: Visual Studio displays the project you just created.
The contents of your first console app appear this way (as shown in Figure 1-3):
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) { } }}
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. You may have to select the Show All Options box.
Choose Projects and Solutions ⇒ General.
Select the new location in the Projects Location field and click OK.
(The examples assume that you have used C:\CSAIO4D for this book.)
You can see the Options dialog box in Figure 1-4. Leave the other fields in the project settings alone for now. Read more about customizing Visual Studio in Book 4 and in Online Chapter 2, which you find by going to www.dummies.com, searching this book’s title, and locating the Downloads tab on the page that appears.
FIGURE 1-4: Changing the default project location.
Along the left edge of the code window, you see several small plus (+) and minus (–) signs in boxes. Click the + sign next to using …. This expands a code region, a handy Visual Studio feature that minimizes clutter. Here are the directives that appear when you expand the region in the default console app:
using System;using System.Collections.Generic;using System.Linq;using System.Text;
Regions help you focus on the code you’re working on by hiding code that you aren’t. Certain blocks of code — such as the namespace block, class block, methods, and other code items — get a +/– automatically without a #region directive. You can add your own collapsible regions, if you like, by typing #region above a code section and #endregion after it. It helps to supply a name for the region, such as Public methods. This code section looks like this:
#region Public methods… your code#endregion Public methods
This name can include spaces. Also, you can nest one region inside another, but regions can’t overlap.
For now, using System; is the only using directive you really need. You can delete the others; the compiler lets you know whether you’re missing one.
Before you try to create your application, open the Output window (if it isn’t already open) by choosing View ⇒ Output. To convert your C# program into an executable program, choose Build ⇒ Build Program1. Visual Studio responds with the following message:
The key point here is the 1 succeeded part on the last line.
As a general rule of programming, succeeded is good; failed is bad. The bad — the exceptions — is covered in Chapter 9 of this minibook.
To execute the program, choose Debug ⇒ Start. The program brings up a black console window and terminates immediately. (If you have a fast computer, the appearance of this window is just a flash on the screen.) The program has seemingly done nothing. In fact, this is the case. The template is nothing but an empty shell.
An alternative command, Debug ⇒ Start Without Debugging, behaves a bit better at this point. Try it out.
The key part of the program you create in the preceding section consists of the final two lines of code:
// Wait for user to acknowledge the results.Console.WriteLine("Press Enter to terminate…");Console.Read();
The easiest way to re-create those key lines in each future console application you write is described in the following sections.
The first step is to save those lines in a handy location for future use: the Toolbox window. With your Program1 console application open in Visual Studio, follow these steps:
In the
Main()
method of class
Program
, select the lines you want to save — in this case, the three lines mentioned previously.
Make sure the Toolbox window is open on the left. (If it isn’t, open it by choosing View ⇒ Toolbox.)
Drag the selected lines into the General tab of the Toolbox window and drop them. (Or copy the lines and paste them into the Toolbox.)
The Toolbox stores the lines there for you in perpetuity. Figure 1-6 shows the lines placed in the Toolbox.
FIGURE 1-6: Setting up the Toolbox with some handy saved text for future use.
Now that you have your template text stored in the Toolbox, you can reuse it in all console applications you write henceforth. Here’s how to use it:
In Visual Studio, create a new console application as described in the section “
Creating the source program
,” earlier in this chapter.
Click in the editor at the spot where you’d like to insert some Toolbox text.
With the Program.cs file open for editing, make sure the Toolbox window is open.
If it isn’t, see the procedure in the preceding “Saving code in the Toolbox” section.
In the General tab of the Toolbox window (other tabs may be showing), find the saved text you want to use and double-click it.
The selected item is inserted at the insertion point in the editor window.
With that boilerplate text in place, you can write the rest of your application above those lines. That’s it. You now have a finished console app. Try it for about 30 seconds. Then you can check out Chapter 2 of this minibook.
Chapter 2
IN THIS CHAPTER
Using C# variables, such as integers, as a storage locker
Declaring other types of variables — dates, characters, strings
Handling numeric constants
Changing types and letting the compiler figure out the type
The most fundamental of all concepts in programming is that of the variable. A C# variable is like a small box in which you can store things, particularly numbers, for later use. (The term variable is borrowed from the world of mathematics.)
Unfortunately for programmers, C# places several limitations on variables — limitations that mathematicians don’t have to consider. However, these limits are in place for a reason. They make it easier for C# to understand what you mean by a particular kind of variable and for you to find mistakes in your code. This chapter takes you through the steps for declaring, initializing, and using variables. It also introduces several of the most basic data types in C#.