36,59 €
Get started with C# and strengthen your knowledge of core programming concepts such as procedural, object-oriented, generic, functional, and asynchronous programming along with the latest features of C# 8
Key Features
Book Description
The C# programming language is often developers' primary choice for creating a wide range of applications for desktop, cloud, and mobile. In nearly two decades of its existence, C# has evolved from a general-purpose, object-oriented language to a multi-paradigm language with impressive features.
This book will take you through C# from the ground up in a step-by-step manner. You'll start with the building blocks of C#, which include basic data types, variables, strings, arrays, operators, control statements, and loops. Once comfortable with the basics, you'll then progress to learning object-oriented programming concepts such as classes and structures, objects, interfaces, and abstraction. Generics, functional programming, dynamic, and asynchronous programming are covered in detail. This book also takes you through regular expressions, reflection, memory management, pattern matching, exceptions, and many other advanced topics. As you advance, you'll explore the .NET Core 3 framework and learn how to use the dotnet command-line interface (CLI), consume NuGet packages, develop for Linux, and migrate apps built with .NET Framework. Finally, you'll understand how to run unit tests with the Microsoft unit testing frameworks available in Visual Studio.
By the end of this book, you'll be well-versed with the essentials of the C# language and be ready to start creating apps with it.
What you will learn
Who this book is for
If you have little experience in coding or C# and want to learn the essentials of C# programming to develop powerful programming techniques, this book is for you. It will also help aspiring programmers to write scripts or programs to accomplish specific tasks.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 749
Veröffentlichungsjahr: 2020
A guide to building a solid foundation in C# language for writing efficient programs
Marius Bancila
Raffaele Rialdi
Ankit Sharma
BIRMINGHAM—MUMBAI
Copyright © 2020 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Commissioning Editor: Richa Tripathi
Acquisition Editor: Alok Dhuri
Senior Editor: Storm Mann
Content Development Editor: Ruvika Rao
Technical Editor: Pradeep Sahu
Copy Editor: Safis Editing
Language Support Editor: Safis Editing
Project Coordinator: Francy Puthiry
Proofreader: Safis Editing
Indexer: Pratik Shirodkar
Production Designer: Jyoti Chauhan
First published: April 2020
Production reference: 1280420
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-78980-586-4
www.packt.com
To my smart boys, Cristian and Bogdan, who love learning new things every day.
– Marius
To my mom and dad, who ignited my passion with a Sinclair ZX81 when I was a child, and to my beautiful wife, Valeria, who has always supported me in my adventures. I love you!
– Raffaele
To my mother, Vibha Sharma, for everything she did for me.
– Ankit
Packt.com
Subscribe to our online digital library for full access to over 7,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
As a developer of the 2020s, it's hard to believe that there was a time in which the choice of programming language was crucial for the success of a software project, with each programming language coming with its own set of libraries defining the range of possible actions. Data access, for example, was a no-brainer in Visual Basic but hard to do in C++, for example. By the same token, calling into low-level Windows API functions was easy in C but sometimes impossible in Visual Basic.
Then came the .NET platform made of two distinct pillars. One pillar was an object-oriented framework defining a wide range of predefined behaviors. The other pillar was a language runtime able to support a variety of programming languages, including Visual Basic and the new C#. Over the years, C# has then become the primary language for the whole .NET platform.
So, what does it mean to learn C# today, two decades after .NET 1.0? Learning the sole syntax and semantics of a programming language makes little to no sense these days, whether it is C#, Java, or Python. A programming language is a largely interchangeable tool with limited real programming power without the backbone of a solid framework.
Subsequently, learning the plain syntax of a programming language is a small fraction of the job and a book that intends to cover any programming language has to go well beyond data types, operators, and control statements. This is precisely what this book does and in addition, in it, you will also explore the authors' well-known obsession through clear and precise topics.
This book is not simply a technical guide about using the C# language. It covers statements, data types, classes, generics, concurrency, and even functional and dynamic programming, plus the array of new features in the latest C# language. However, if you are only armed with these tools, you won't go too far even with building toy applications. It is also important for you to know about the foundational aspects of the .NET platform, such as reflection, collections, regular expressions, files, streams, serialization, and LINQ.
Anything else? You bet!
Error handling, exceptions, garbage collection, and memory management also have a reserved chapter, before ending with an overview of C#8 in the context of .NET Core 3 and unit testing.
In spite of the title, this is not simply the umpteenth book on a popular programming language. It is a book about how to use a popular programming language to its fullest for building .NET applications on a solid foundation.
Dino Esposito
Digital Strategist, Youbiquitous.net
Marius Bancila is a software engineer with almost two decades of experience in developing solutions for the industrial and financial sectors. He is the author of Modern C++ Programming Cookbook and The Modern C++ Challenge. He works as a software architect and is focused on Microsoft technologies, mainly developing desktop applications with C++ and C#, but not solely. He is passionate about sharing his technical expertise with others and, for that reason, he has been recognized as a Microsoft MVP for C++ and later developer technologies since 2006.
I would like to thank everybody that made this book possible. To Raffaele and Ankit for laboring on this project together and making it a great book. To Omprakash for his useful comments. To Ruvika for all her support and patience during the project. To Alok, Storm, and all the other people at Packt that helped turn this book from an idea to reality.
Raffaele Rialdi is a senior software architect working as a consultant, speaker, and trainer. Since 2003, he is a Microsoft MVP in the Developer Security category. His passion for the community leads him to be a member of the board of UGIdotNET, president of DotNetLiguria, and co-founder of the Italian C++ user group. Currently, he is working as an architect and developer on the backend of an enterprise project with a specific focus on code generation, and working on cross-platform mobile and IoT development in both C# and C++. You can find him on Twitter with the handle @raffaeler.
A big thank you goes to my fellow co-authors, Marius and Ankit, for their great work; Omprakash for his valuable reviews; the entire Packt team, who did a great job in letting me work with peace of mind; and, last but not least, Ruvika for her great patience in coordinating with all of us.
Ankit Sharma is a software engineer currently working as Senior Member Technical with ADP in Hyderabad, India. He has over six years of extensive experience with Microsoft technologies, including C#, ASP.NET, and SQL Server, and UI technologies such as jQuery, Angular, and Blazor. Ankit is a technical author and speaker and loves to contribute to the open source community. He writes articles for multiple platforms, including c-sharpcorner, Dzone, Medium, and freeCodeCamp. For his dedicated contribution to the developer's community, he has been recognized as c-sharpcorner MVP, Dzone MVB, and a top contributor in the technology category on Medium. He is also the author of the first ever book on Blazor – Blazor Quick Start Guide. You can tweet him at @ankitsharma_007.
I would like to thank my mother for her continuous support throughout the process of writing this book.
I would also like to thank my co-authors, Marius and Raffaele, for their constructive feedback throughout the writing process, which was crucial in enhancing the quality of the content.
Omprakash Pandey is a seasoned software technology professional associated with Synergetics. He has provided innovative solutions on C, C++, Java (Core, Intermediate, and Advanced), .NET (Basic), ADO.NET, WCF, WF, ASP.NET MVC, Microsoft 365, Microsoft Azure, infrastructure management for portal development and deployment, and services development.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
C# is a general-purpose, multi-paradigm programming language that combines object-oriented, imperative, generic, functional, declarative, and dynamic programming. Soon after its release, C# became one of the top choices for developers for writing a large variety of types of applications. Although it is not the only language targeting the CLI (the others include VB.NET and F#), it is the primary choice for writing .NET applications for desktop, web, cloud, and mobile platforms.
Over the years, the language has evolved gradually but steadily. Although initially it was an object-oriented programming language, new versions have opened up the language to new paradigms such as generic, functional, and dynamic programming. New language features and more concise syntax have also been added regularly. With its release as an open source project of the .NET Compiler Platform, also known as Roslyn, which is a set of compilers and code analysis APIs for C# and VB.NET, the language has entered a new open era with the community deeply involved in the development of the language.
The current version of the language is known as C# 8. This was released in September 2019 for .NET Core 3.0 and requires Visual Studio 2019 16.3 or a newer version. C# 8 can also be used with .NET Framework, although not all features are available. That is because they required runtime changes, which was something Microsoft did not want to do due to its intent to no longer invest in .NET Framework (other than long-time support) and turn .NET Core into the one framework used to target all platforms and types of applications. This framework will be known simply as .NET.
This book is designed to help you learn the language from scratch and eventually master all its multi-paradigm programming aspects. We start with the very basics: data types, statements, and other building blocks. We then continue with object-oriented concepts such as classes, interfaces, inheritance, and polymorphism. We cover generics, functional programming and LINQ, reflection and dynamic programming, and more advanced topics, such as resource management, pattern matching, concurrency and asynchronous programming, error handling, and serialization. Toward the end of the book, we give special attention to the new features introduced in C# 8. Last, but not least, we discuss unit testing and how you can write unit tests for your C# code. At the end of each chapter, we provide you with a set of questions to help you assess what you learned in that chapter.
The book contains many code snippets that are designed to help you easily understand and learn all the language features. All of them are available in the source code that accompanies the book. You will need either Visual Studio or Visual Studio Code to try them. Alternatively, you can use an online compiler, the primary choice in this case being https://sharplab.io/.
If you are a passionate programmer and want to learn C#, this book is for you. If you want to start learning to program and want to do that with C# and .NET, you will also find the book valuable. However, we assume you have some basic knowledge of programming concepts, such as what a compiler is, what classes and methods are, and so on. On the other hand, if you are an experienced C# programmer but want to learn about the latest features of C# 8 or how to work with .NET Core and migrate from .NET Framework, this book will be handy for you, too.
Chapter 1, Starting with the Building Blocks of C#, gives an introduction to the language, its history, and its relationship with the Common Language Infrastructure and .NET Framework, as well as providing an introduction to the family of .NET frameworks used today. At the end, you learn about assemblies, how to create a project in Visual Studio, and how to write a Hello World program in C#.
Chapter 2, Data Types and Operators, walks you through the basic elements of the language, including the built-in data types, variables and constants, reference, and value types, nullable types, and array types, as well as type conversions and built-in operators.
Chapter 3, Control Statements and Exceptions, looks in depth at how to write selection statements and loops and briefly at working with exceptions.
Chapter 4, Understanding the Various User-Defined Types, provides information about classes, fields, properties, methods, constructors, how to pass arguments to methods, what access modifiers are, and other aspects related to classes. Toward the end, you will learn about structures and how they compare to classes, as well as enumerations.
Chapter 5, Object-Oriented Programming in C#, continues on the foundation built with the previous chapter and teaches you the core pillars of object-oriented programming and how you achieve them using C# language features such as interfaces, virtual members, method overloading, and others.
Chapter 6, Generics, covers all the aspects of generic programming in C# and teaches you how to write generic types and methods and use constraints for type parameters.
Chapter 7, Collections, provides a walk-through of the generic collections from the .NET base class library that you typically use when writing C# programs. The chapter ends with an overview of the concurrent collections used in multithreading scenarios.
Chapter 8, Advanced Topics, contains a variety of more advanced features, such as delegates and events, tuples, extension methods, pattern matching, and regular expressions.
Chapter 9, Resource Management, explains how the garbage collector works and how you should handle resources deterministically. Also, in this chapter, you learn how to make system or, in general, native API calls with Platform Invocation Services, as well as how to write unsafe code.
Chapter 10, Lambdas, LINQ, and Functional Programming, provides an overview of functional programming concepts and details pertaining to lambda expressions in C#. You learn how to uniformly query various data sources using Language Integrated Query (or LINQ). At the end of the chapter, we cover several typical functional programming concepts: partial function application, currying, closures, monoids, and monads and how they work in C#.
Chapter 11, Reflection and Dynamic Programming, teaches you what reflection services are and how they can be used to write extensible applications, how to dynamically load assemblies and execute code, how to use attributes, and how to use the Dynamic Language Runtime and the dynamic type to interop with dynamic languages.
Chapter 12, Multithreading and Asynchronous Programming, provides an in-depth look at threads, tasks, and synchronization mechanisms and uncovers the details of the async-await pattern for writing asynchronous programs in C#.
Chapter 13, Files, Streams, and Serialization, explains how to work with paths, files, and directories, and how to use streams for reading and writing data from and to a variety of storage options, such as files and memory. In the second part of the chapter, you will learn about data serialization with XML and JSON.
Chapter 14, Error Handling, builds on the concepts concerning exception handling introduced in Chapter 3, Control Statements and Exceptions, and teaches you the inner workings of exceptions and how exception handling differs from error handling. You will learn valuable information about debugging and monitoring as well as best practices for working with exceptions.
Chapter 15, New Features of C# 8, covers in detail all the new language features introduced in C# 8, including nullable reference types, async streams, ranges and indices, pattern matching, and default implementations of interface members.
Chapter 16, C# in Action with .NET Core 3, teaches you about using the .NET CLI for building .NET Core applications, how you can target and develop for Linux, what .NET Standard is and how it can help application design, how to consume NuGet packages, and how you can migrate .NET Framework applications to .NET Core.
Chapter 17, Unit Testing, covers unit testing, the Microsoft tools for unit testing your C# code, how to create unit testing projects using Visual Studio, and how to write unit tests and data-driven unit tests.
This is a book that covers C#, from its building blocks to its most advanced features. This book is intended for people who want to learn C#. Therefore, we do not expect you to have any prior knowledge of the language. However, we do expect you to have some basic exposure to programming concepts, such as what a compiler is, the difference between compile time and runtime, the difference between stack and heap, and others.
All the code samples in this book have been written using C# 8 and a modern programming style (such as using expression-bodied members, interpolated strings, local functions, and so on). All these samples are available together with the book in projects targeting .NET Core 3.1.
The following table lists the software and platform requirements for running these samples:
In order to run the source code, you need Visual Studio 2019 16.3 or newer, any edition, or Visual Studio Code. Most of the samples can also be tested using an online compiler. Should you prefer this option, we recommend that you use https://sharplab.io/.
If you are using the digital version of this book, we advise you to type the code yourself or access the code via the GitHub repository (link available in the next section). Doing so will help you avoid any potential errors related to the copying/pasting of code.
You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at www.packt.com.Select the Support tab.Click on Code Downloads.Enter the name of the book in the Search box and follow the onscreen instructions.Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for WindowsZipeg/iZip/UnRarX for Mac7-Zip/PeaZip for LinuxThe code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Learn-C-Sharp-Programming. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
Code in Action videos for this book can be viewed at https://bit.ly/2VaAls9.
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://static.packt-cdn.com/downloads/9781789805864_ColorImages.pdf.
There are a number of text conventions used throughout this book.
Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "In this example, we are creating an Employee class with three fields to represent the ID, first name, and last name of an employee."
A block of code is set as follows:
class Employee
{
public int EmployeeId;
public string FirstName;
public string LastName;
}
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
public struct Vector
{
public float x;
public float y;
private readonly float SquaredRo => (x * x) + (y * y);
public readonly float GetLengthRo() => MathF.Sqrt(SquaredRo);
public float GetLength() => MathF.Sqrt(SquaredRo);
}
Any command-line input or output is written as follows:
cd HelloSolution
dotnet new console -o Hello
dotnet sln add Hello
Bold: Indicates a new term, an important word, or words that you see on screen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "When creating a new project, select Console App (.NET Core)."
Tips or important notes
Appear like this.
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected]
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in, and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packt.com.