Skip to main content
Top

Pro C# 9 with .NET 5

Foundational Principles and Practices in Programming

  • 2021
  • Book
insite
SEARCH

About this book

This essential classic provides a comprehensive foundation in the C# programming language and the framework it lives in. Now in its 10th edition, you will find the latest C# 9 and .NET 5 features served up with plenty of "behind the curtain" discussion designed to expand developers’ critical thinking skills when it comes to their craft. Coverage of ASP.NET Core, Entity Framework Core, and more, sits alongside the latest updates to the new unified .NET platform, from performance improvements to Windows Desktop apps on .NET 5, updates in XAML tooling, and expanded coverage of data files and data handling. Going beyond the latest features in C# 9, all code samples are rewritten for this latest release.

Dive in and discover why this book is a favorite of C# developers worldwide. Gain a solid foundation in object-oriented development techniques, attributes and reflection, generics and collections, and numerous advanced topics not found in other texts (such as CIL opcodes and emitting dynamic assemblies). With the help of Pro C# 9 with .NET 5 you will gain the confidence to put C# into practice, and explore the .NET universe and its vast potential on your own terms.

What You Will Learn

Explore C# 9 features and updates in records, immutable classes, init only setters, top-level statements, patterns, and moreHit the ground running with ASP.NET Core web applications and web servicesEmbrace Entity Framework Core for building real-world, data-centric applications, with deeply expanded coverage new to this editionDevelop applications with C# and modern frameworks for services, web, and smart client applicationsUnderstand the philosophy behind .NET Discover the new features in .NET 5, including single file applications and smaller container images, Windows ARM64 support, and more Dive into Windows Desktop Apps on .NET 5 using Windows Presentation Foundation Check out performance improvements included with updates to ASP.NET Core, Entity Framework Core, and internals like garbage collection, System.Text.Json, and container size optimization

Who This Book Is For

Developers who are interested in .NET programming and the C# language

“Amazing! Provides easy-to-follow explanations and examples. I remember reading the first version of this book; this is a ‘must-have’ for your collection if you are learning .NET!”

– Rick McGuire, Senior Application Development Manager, Microsoft

“Phil is a journeyman programmer who brings years of experience and a passion for teaching to make this fully revised and modernized ‘classic’ a ‘must-have’. Any developer who wants full-spectrum, up-to-date coverage of both the C# language and how to use it with .NET and ASP.NET Core should get this book.”

– Brian A. Randell, Partner, MCW Technologies and Microsoft MVP

Table of Contents

Frontmatter

Introducing C# and .NET 5

Frontmatter
Chapter 1. Introducing C# and .NET (Core) 5

Microsoft’s .NET platform and the C# programming language were formally introduced circa 2002 and have quickly become a mainstay of modern-day software development. The .NET platform enables a large number of programming languages (including C#, VB.NET, and F#) to interact with each other. A program written in C# can be referenced by another program written in VB.NET. More on this interoperability later in this chapter.

Andrew Troelsen, Phillip Japikse
Chapter 2. Building C# Applications

As a C# programmer, you can choose from among numerous tools to build .NET Core applications. The tool (or tools) you select will be based primarily on three factors: any associated costs, the OS you are using to develop the software, and the computing platforms you are targeting. The point of this chapter is to provide the information you need to install the .NET 5 SDK and runtime and to present a first look at Microsoft’s flagship IDEs, Visual Studio Code and Visual Studio.

Andrew Troelsen, Phillip Japikse

Core C# Programming

Frontmatter
Chapter 3. Core C# Programming Constructs, Part 1

This chapter begins your formal investigation of the C# programming language by presenting a number of bite-sized, stand-alone topics you must be comfortable with as you explore the .NET Core Framework. The first order of business is to understand how to build your program’s application object and to examine the composition of an executable program’s entry point: the Main() method as well as a new C# 9.0 feature, top-level statements. Next, you will investigate the fundamental C# data types (and their equivalent types in the System namespace) including an examination of the System.String and System.Text.StringBuilder classes.

Andrew Troelsen, Phillip Japikse
Chapter 4. Core C# Programming Constructs, Part 2

This chapter picks up where Chapter 3 left off and completes your investigation of the core aspects of the C# programming language. You will start with an investigation of the details behind manipulating arrays using the syntax of C# and get to know the functionality contained within the related System.Array class type.

Andrew Troelsen, Phillip Japikse

Object Oriented Programming with C#

Frontmatter
Chapter 5. Understanding Encapsulation

In Chapters 3 and 4, you investigated a number of core syntactical constructs that are commonplace to any .NET Core application you might be developing. Here, you will begin your examination of the object-oriented capabilities of C#. The first order of business is to examine the process of building well-defined class types that support any number of constructors. After you understand the basics of defining classes and allocating objects, the remainder of this chapter will examine the role of encapsulation. Along the way, you will learn how to define class properties and come to understand the details of the static keyword, object initialization syntax, read-only fields, constant data, and partial classes.

Andrew Troelsen, Phillip Japikse
Chapter 6. Understanding Inheritance and Polymorphism

Chapter 5 examined the first pillar of OOP: encapsulation. At that time, you learned how to build a single well-defined class type with constructors and various members (fields, properties, methods, constants, and read-only fields). This chapter will focus on the remaining two pillars of OOP: inheritance and polymorphism.

Andrew Troelsen, Phillip Japikse
Chapter 7. Understanding Structured Exception Handling

In this chapter, you will learn how to handle runtime anomalies in your C# code through the use of structured exception handling. Not only will you examine the C# keywords that allow you to handle such matters (try, catch, throw, finally, when), but you will also come to understand the distinction between application-level and system-level exceptions, as well as the role of the System.Exception base class. This discussion will lead into the topic of building custom exceptions and, finally, to a quick look at some exception-centric debugging tools of Visual Studio.

Andrew Troelsen, Phillip Japikse
Chapter 8. Working with Interfaces

This chapter builds upon your current understanding of object-oriented development by examining the topic of interface-based programming. Here, you will learn how to define and implement interfaces and come to understand the benefits of building types that support multiple behaviors. Along the way, you will look at several related topics, such as obtaining interface references, implementing explicit interfaces, and constructing interface hierarchies. You will also examine several standard interfaces defined within the .NET Core base class libraries. Also covered are the new features in C# 8 regarding interfaces, including default interface methods, static members, and access modifiers. As you will see, your custom classes and structures are free to implement these predefined interfaces to support several useful behaviors, such as object cloning, object enumeration, and object sorting.

Andrew Troelsen, Phillip Japikse
Chapter 9. Understanding Object Lifetime

At this point in the book, you have learned a great deal about how to build custom class types using C#. Now you will see how the runtime manages allocated class instances (aka objects) via garbage collection (GC). C# programmers never directly deallocate a managed object from memory (recall there is no delete keyword in the C# language). Rather, .NET Core objects are allocated to a region of memory termed the managed heap, where they will be automatically destroyed by the garbage collector “sometime in the future.”

Andrew Troelsen, Phillip Japikse

Advanced C# Programming

Frontmatter
Chapter 10. Collections and Generics

Any application you create with the .NET Core platform will need to contend with the issue of maintaining and manipulating a set of data points in memory. These data points can come from any variety of locations including a relational database, a local text file, an XML document, a web service call, or perhaps user-provided input.

Andrew Troelsen, Phillip Japikse
Chapter 11. Advanced C# Language Features

In this chapter, you’ll deepen your understanding of the C# programming language by examining several more advanced topics. To begin, you’ll learn how to implement and use an indexer method. This C# mechanism enables you to build custom types that provide access to internal subitems using an array-like syntax. After you learn how to build an indexer method, you’ll see how to overload various operators (+, -, <, >, etc.) and how to create custom explicit and implicit conversion routines for your types (and you’ll learn why you might want to do this).

Andrew Troelsen, Phillip Japikse
Chapter 12. Delegates, Events, and Lambda Expressions

Up to this point in the text, most of the applications you have developed added various bits of code to Program.cs as top-level statements, which, in some way or another, sent requests to a given object. However, many applications require that an object be able to communicate back to the entity that created it using a callback mechanism. While callback mechanisms can be used in any application, they are especially critical for graphical user interfaces in that controls (such as a button) need to invoke external methods under the correct circumstances (when the button is clicked, when the mouse enters the button surface, etc.).

Andrew Troelsen, Phillip Japikse
Chapter 13. LINQ to Objects

Regardless of the type of application you are creating using the .NET Core platform, your program will certainly need to access some form of data as it executes. To be sure, data can be found in numerous locations, including XML files, relational databases, in-memory collections, and primitive arrays. Historically speaking, based on the location of said data, programmers needed to use different and unrelated APIs. The Language Integrated Query (LINQ) technology set, introduced initially in .NET 3.5, provides a concise, symmetrical, and strongly typed manner to access a wide variety of data stores. In this chapter, you will begin your investigation of LINQ by focusing on LINQ to Objects.

Andrew Troelsen, Phillip Japikse
Chapter 14. Processes, AppDomains, and Load Contexts

In this chapter, you’ll drill deep into the details of how an assembly is hosted by the runtime and come to understand the relationship between processes, application domains, and object contexts.

Andrew Troelsen, Phillip Japikse
Chapter 15. Multithreaded, Parallel, and Async Programming

Nobody enjoys working with an application that is sluggish during its execution. Moreover, nobody enjoys starting a task in an application (perhaps initiated by clicking a toolbar item) that prevents other parts of the program from being as responsive as possible. Before the release of .NET (and .NET Core), building applications that had the ability to perform multiple tasks typically required authoring complex C++ code that used the Windows threading APIs. Thankfully, the .NET/.NET Core platform provides several ways for you to build software that can perform complex operations on unique paths of execution, with far fewer pain points.

Andrew Troelsen, Phillip Japikse

Programming with .NET Core Assemblies

Frontmatter
Chapter 16. Building and Configuring Class Libraries

For most of the examples so far in this book, you have created “stand-alone” executable applications, in which all the programming logic was packaged within a single assembly (*.dll) and executed using dotnet.exe (or a copy of dotnet.exe named after the assembly). These assemblies were using little more than the .NET Core base class libraries. While some simple .NET Core programs may be constructed using nothing more than the base class libraries, chances are it will be commonplace for you (or your teammates) to isolate reusable programming logic into custom class libraries (*.dll files) that can be shared among applications.

Andrew Troelsen, Phillip Japikse
Chapter 17. Type Reflection, Late Binding, and Attribute-Based Programming

As shown in Chapter 16 , assemblies are the basic unit of deployment in the .NET Core universe. Using the integrated Object Browser of Visual Studio (and numerous other IDEs), you can examine the types within a project’s referenced set of assemblies. Furthermore, external tools such as ildasm.exe allow you to peek into the underlying CIL code, type metadata, and assembly manifest for a given .NET Core binary. In addition to this design-time investigation of .NET Core assemblies, you are also able to programmatically obtain this same information using the System.Reflection namespace. To this end, the first task of this chapter is to define the role of reflection and the necessity of .NET Core metadata.

Andrew Troelsen, Phillip Japikse
Chapter 18. Dynamic Types and the Dynamic Language Runtime

NET 4.0 introduced a new keyword to the C# language, specifically, dynamic. This keyword allows you to incorporate scripting-like behaviors into the strongly typed world of type safety, semicolons, and curly brackets. Using this loose typing, you can greatly simplify some complex coding tasks and also gain the ability to interoperate with a number of dynamic languages that are .NET Core savvy.

Andrew Troelsen, Phillip Japikse
Chapter 19. Understanding CIL and the Role of Dynamic Assemblies

When you are building a full-scale .NET Core application, you will most certainly use C# (or a similar managed language such as Visual Basic), given its inherent productivity and ease of use. However, as you learned in the beginning of this book, the role of a managed compiler is to translate *.cs code files into terms of CIL code, type metadata, and an assembly manifest. As it turns out, CIL is a full-fledged .NET Core programming language, with its own syntax, semantics, and compiler (ilasm.exe).

Andrew Troelsen, Phillip Japikse

File Handling, Object Serialization, and Data Access

Frontmatter
Chapter 20. File I/O and Object Serialization

When you create desktop applications, the ability to save information between user sessions is commonplace. This chapter examines several I/O-related topics as seen through the eyes of the .NET Core Framework. The first order of business is to explore the core types defined in the System.IO namespace and learn how to modify a machine’s directory and file structure programmatically. The next task is to explore various ways to read from and write to character-based, binary-based, string-based, and memory-based data stores.

Andrew Troelsen, Phillip Japikse
Chapter 21. Data Access with ADO.NET

The .NET Core platform defines several namespaces that allow you to interact with relational database systems. Collectively speaking, these namespaces are known as ADO.NET. In this chapter, you will learn about the overall role of ADO.NET and the core types and namespaces, and then you will move on to the topic of ADO.NET data providers. The .NET Core platform supports numerous data providers (both provided as part of the .NET Core Framework and available from third-party sources), each of which is optimized to communicate with a specific database management system (e.g., Microsoft SQL Server, Oracle, and MySQL).

Andrew Troelsen, Phillip Japikse

Entity Framework Core

Frontmatter
Chapter 22. Introducing Entity Framework Core

The previous chapter examined the fundamentals of ADO.NET. ADO.NET has enabled .NET programmers to work with relational data (in a relatively straightforward manner) since the initial release of the .NET platform. Building on ADO.NET, Microsoft introduced a new component of the ADO.NET API called the Entity Framework (or simply, EF) in .NET 3.5 Service Pack 1.

Andrew Troelsen, Phillip Japikse
Chapter 23. Build a Data Access Layer with Entity Framework Core

The previous chapter covered the details of EF Core and its capabilities. This chapter is focused on applying what you learned about EF Core to build the AutoLot data access layer. You begin the chapter by scaffolding the entities and derived DbContext from the previous chapter’s database. Then the project is changed from database first to code first, and the entities are updated to their final version and applied to the database using EF Core migrations. The final change to the database is to re-create the GetPetName stored procedure and create a new database view (complete with a matching view model), all using migrations.

Andrew Troelsen, Phillip Japikse

Windows Client Development

Frontmatter
Chapter 24. Introducing Windows Presentation Foundation and XAML

When version 1.0 of the .NET platform was released, programmers who needed to build graphical desktop applications made use of two APIs named Windows Forms and GDI+, packaged up primarily in the System.Windows.Forms.dll and System.Drawing.dll assemblies. While Windows Forms and GDI+ are still viable APIs for building traditional desktop GUIs, Microsoft shipped an alternative GUI desktop API named Windows Presentation Foundation (WPF) beginning with the release of .NET 3.0. WPF and Windows Forms joined the .NET Core family with the release of .NET Core 3.0.

Andrew Troelsen, Phillip Japikse
Chapter 25. WPF Controls, Layouts, Events, and Data Binding

Chapter 24 provided a foundation for the WPF programming model, including an examination of the Window and Application classes, the grammar of XAML, and the use of code files. Chapter 24 also introduced you to the process of building WPF applications using the designers of Visual Studio. In this chapter, you will dig into the construction of more sophisticated graphical user interfaces using several new controls and layout managers, learning about additional features of the WPF Visual Designer for XAML of Visual Studio along the way.

Andrew Troelsen, Phillip Japikse
Chapter 26. WPF Graphics Rendering Services

In this chapter, you’ll examine the graphical rendering capabilities of WPF. As you’ll see, WPF provides three separate ways to render graphical data: shapes, drawings, and visuals. After you understand the pros and cons of each approach, you will start learning about the world of interactive 2D graphics using the classes within System.Windows.Shapes. After this, you’ll see how drawings and geometries allow you to render 2D data in a more lightweight manner. Finally, you’ll learn how the visual layer gives you the greatest level of power and performance.

Andrew Troelsen, Phillip Japikse
Chapter 27. WPF Resources, Animations, Styles, and Templates

This chapter introduces you to three important (and interrelated) topics that will deepen your understanding of the Windows Presentation Foundation (WPF) API. The first order of business is to learn the role of logical resources. As you will see, the logical resource (also known as an object resource) system is a way to name and refer to commonly used objects within a WPF application. While logical resources are often authored in XAML, they can also be defined in procedural code.

Andrew Troelsen, Phillip Japikse
Chapter 28. WPF Notifications, Validations, Commands, and MVVM

This chapter will conclude your investigation of the WPF programming model by covering the capabilities that support the Model-View-ViewModel (MVVM) pattern. The first section covers the Model-View-ViewModel pattern. Next, you learn about the WPF notification system and its implementation of the Observable pattern through observable models and observable collections. Having the data in the UI accurately portray the current state of the data automatically improves the user experience significantly and reduces the manual coding required in older technologies (such as WinForms) to achieve the same result.

Andrew Troelsen, Phillip Japikse

ASP.NET Core

Frontmatter
Chapter 29. Introducing ASP.NET Core

The final section of this book covers ASP.NET Core, the latest version of the web development framework that uses C# and .NET Core. This chapter introduces ASP.NET Core and some of the changes from the previous version of the web development framework, ASP.NET.

Andrew Troelsen, Phillip Japikse
Chapter 30. RESTful Services with ASP.NET Core

The previous chapter introduced ASP.NET Core, talked about some of the new features, created the projects, and updated the code in AutoLot.Mvc and AutoLot.Api to include the AutoLot.Dal and Serilog logging. This chapter focuses on completing that AutoLot.Api RESTful service.

Andrew Troelsen, Phillip Japikse
Chapter 31. MVC Applications with ASP.NET Core

Chapter 29 laid the foundation for ASP.NET Core, and in Chapter 30 , we built the RESTful service. In this chapter, we will build the web application using the MVC pattern. We begin by putting the V back into MVC.

Andrew Troelsen, Phillip Japikse
Backmatter
Title
Pro C# 9 with .NET 5
Authors
Andrew Troelsen
Phillip Japikse
Copyright Year
2021
Publisher
Apress
Electronic ISBN
978-1-4842-6939-8
Print ISBN
978-1-4842-6938-1
DOI
https://doi.org/10.1007/978-1-4842-6939-8

Accessibility information for this book is coming soon. We're working to make it available as quickly as possible. Thank you for your patience.

Premium Partner

    Image Credits
    Neuer Inhalt/© ITandMEDIA, Nagarro GmbH/© Nagarro GmbH, AvePoint Deutschland GmbH/© AvePoint Deutschland GmbH, AFB Gemeinnützige GmbH/© AFB Gemeinnützige GmbH, USU GmbH/© USU GmbH