Copyright © 2021 by John Wiley & Sons, Inc. All rights reserved.
Published by John Wiley & Sons, Inc., Hoboken, New Jersey.
Published simultaneously in Canada.
ISBN: 978‐1‐119‐79578‐0
ISBN: 978‐1‐119‐79582‐7 (ebk)
ISBN: 978‐1‐119‐79583‐4 (ebk)
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 Section 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per‐copy fee to the Copyright Clearance Center, Inc., 222 Rosewood Drive, Danvers, MA 01923, (978) 750‐8400, fax (978) 750‐4470, or on the web at www.copyright.com
. 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/permission
.
Limit of Liability/Disclaimer of Warranty: While the publisher and author have used their best efforts in preparing this book, they make no representations or warranties with respect to the accuracy or completeness of the contents of this book and specifically disclaim any implied warranties of merchantability or fitness for a particular purpose. No warranty may be created or extended by sales representatives or written sales materials. The advice and strategies contained herein may not be suitable for your situation. You should consult with a professional where appropriate. Neither the publisher nor author shall be liable for any loss of profit or any other commercial damages, including but not limited to special, incidental, consequential, or other damages.
For general information on our other products and services or for technical support, please contact our Customer Care Department within the United States at (800) 762‐2974, outside the United States at (317) 572‐3993 or fax (317) 572‐4002.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic formats. For more information about Wiley products, visit our web site at www.wiley.com
.
Library of Congress Control Number: 2021938274
Trademarks: WILEY and the Wiley logo are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries, 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.
Cover Image: ©Ben Clift Williams/EyeEm/Getty Images
Cover Design: Wiley
Benjamin Perkins is currently employed at Microsoft in Munich, Germany, as a Senior Escalation Engineer for IIS, ASP.NET, and Azure App Services. He has been working professionally in the IT industry for over two decades. He started computer programming with QBasic at the age of 11 on an Atari 1200XL desktop computer. He takes pleasure in the challenges that troubleshooting technical issues have to offer and savors in the rewards of a well‐written program. After completing high school, he joined the United States Army. After successfully completing his military service, he attended Texas A&M University in College Station, Texas, where he received a Bachelor of Business Administration in Management Information Systems. He also received a Master of Business Administration from the European University.
His roles in the IT industry have spanned the entire spectrum including programmer, system architect, technical support engineer, team leader, and mid‐level management. While employed at Hewlett‐Packard, he received numerous awards, degrees, and certifications. He has a passion for technology and customer service and looks forward to troubleshooting and writing more world‐class technical solutions. “My approach is to write code with support in mind, and to write it once correctly and completely so we do not have to come back to it again, except to enhance it.”
Benjamin has written numerous magazine articles and training courses and is an active blogger. His catalog of books covers C# Programming, IIS, NHibernate, Open Source, and Microsoft Azure.
www.linkedin.com/in/csharpguitar
twitter.com/csharpguitar
www.thebestcsharpprogrammerintheworld.com
github.com/benperk
Benjamin is married to Andrea and has two wonderful children, Lea and Noa.
Jon D. Reid is a Program Manager in Research and Development for IFS AB (www.ifs.com
) focusing on Field Service Management. He has coauthored many books on Microsoft technologies, including Beginning C# 7 Programming with Visual Studio 2017, Fast Track C#, Pro Visual Studio .NET, and many others.
Rod Stephens is a long‐time developer and author who has written more than 250 magazine articles and 35 books that have been translated into different languages around the world. During his career, Rod has worked on an eclectic assortment of applications in such fields as telephone switching, billing, repair dispatching, tax processing, wastewater treatment, concert ticket sales, cartography, and training for professional football teams.
Rod's popular C# Helper website (www.csharphelper.com
) receives millions of hits per year and contains tips, tricks, and example programs for C# programmers. His VB Helper website (www.vb-helper.com
) contains similar material for Visual Basic programmers.
You can contact Rod at: RodStephens@csharphelper.com
or RodStephens@vb-helper.com
.
It takes a lot of work to get content into a presentable format for students and IT professionals to read and get value from. The authors indeed have technical knowledge and experiences to share, but without the technical writers, technical reviewers, developers, editors, publishers, graphic designers, the list goes on, providing their valuable input, a book of high quality could not be written. The rate of change occurs too quickly for an individual to perform all these tasks and still publish a book that is valid before the technology becomes stale. This is why authors worked together with great teams to get all the components of the book together quickly. It was done to ensure that the most up‐to‐date information gets to the reader while the features are still fresh and current. I would like to thank Rod Stephens for his technical review and suggestions throughout the process. Lastly, I would like to thank all the numerous people behind the scenes who helped get this book together.
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:
This book is divided into four sections:
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.
As for styles in the text:
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.
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.