Implementing
Design Patterns in C# 11 and .NET 7
2nd Edition
Learn how to design and develop robust and
scalable applications using design patterns
Alexandre F. Malavasi Cardoso
www.bpbonline.com
Copyright © 2024 BPB Online
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 author, nor BPB Online 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.
BPB Online has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, BPB Online cannot guarantee the accuracy of this information.
First published: 2021 Second published: 2024
Published by BPB Online WeWork
119 Marylebone Road London NW1 5PU
UK | UAE | INDIA | SINGAPORE ISBN 978-93-55517-333
www.bpbonline.com
Dedicated to
My beloved wife:
Paula and
My daughter Myla
About the Author
Alexandre F. Malavasi Cardoso boasts over 16 years in software
development, taking pivotal roles as a technical leader and engineer. He has spearheaded major projects using Microsoft Technologies for prominent companies across South America, Europe, and the U.S. Presently, he serves as the Head of Engineering at Propylon and as a Technical Advisor for Marelo. Alexandre’s academic accolades include a postgraduate degree in Business and Systems Analysis and two master’s degrees emphasizing Software Engineering with Agile Methods. He has earned multiple Microsoft certifications in Azure and Web Development. An active contributor to the global tech community, Alexandre often speaks at
international IT conferences, authors technical articles, and has thrice been recognized by Microsoft as a Most Valuable Professional (MVP).
About the Reviewer
Based in Rabat, Morocco, Nabil Tadili stands out as a renowned Lead Software Architect with deep expertise in Full Stack development, predominantly in the realms of .NET and Angular. With an unwavering dedication to pioneering innovations and adhering to industry best
practices, he’s delved profoundly into these platforms, ensuring he’s attuned to their evolving nuances. In addition, Nabil showcases mastery in Node, Svelte, NextJs, Python, and a plethora of databases and demonstrates an exceptional command over CI/CD methodologies, representing a
comprehensive embodiment of contemporary software engineering.
At Orange Business, Nabil’s key role in driving the shift to a Microservices architecture highlights his forward-thinking approach to technological progression. While actively delving into Machine Learning at the Georgia Institute of Technology, he further accentuates his multifaceted expertise by refining business workflows and leading groundbreaking digital projects.
His freelance journey, punctuated by over 150 accomplished projects and a stellar 98%+ client satisfaction rate, underscores his flexibility and
unwavering commitment.
Ever driven by the motto to challenge one’s limits, Nabil is an ardent advocate for teamwork, innovation, and continuous learning. His passion extends to artificial intelligence, quantum computing, and science.
Acknowledgement
My heartfelt appreciation goes to my family and friends for their steadfast support during this book’s creation, with a special nod to my wife Paula and daughter Myla. I extend my gratitude to BPB Publications, whose expertise was pivotal in finalizing this work—a journey enriched by the collaboration of reviewers, technical mavens, and editors.
I must also recognize the invaluable insights of my colleagues and
coworkers from years in the tech sector. Their teachings and feedback have been indispensable. Lastly, to every reader who resonated with my book:
your enthusiasm and encouragement have truly anchored this endeavor.
Preface
In the dynamic world of software development, the mastery of Design Patterns and the intricacies of the object-oriented programming paradigm can set one apart. This book aims to be your guide through these
complexities, specifically tailored for the modern version of C# language and the .NET platform. Our journey spans from the foundational SOLID principles, traces the rich history of the .NET platform, and ventures into the core of Design Patterns, all illustrated through tangible, real-world examples and an intuitive, step-by-step methodology.
Our opening chapters lay the groundwork, elucidating the fundamental concepts of C# and .NET. As we traverse through SOLID principles and the essence of object-oriented programming, we set the stage for the immersive experiences that follow. The book’s heart revolves around hands-on
examples that emphasize best software development practices, all while setting the stage for the profound Design Patterns which dominate the contemporary market.
Upon turning the last page, you, the developer, will find yourself equipped with a holistic understanding of C# and the .NET platform. More than just knowledge, you’ll possess the practical wisdom to implement best practices in real-world scenarios and a versatile toolbox of Design Patterns to tackle the myriad challenges of software development. Welcome to a
transformative learning experience.
Chapter 1: C# Fundamentals – Diving deep into the C# landscape, this chapter covers the essential components of the language—from its syntax to control structures. Readers will become well-versed with data types,
operators, and the nuances of C# development, setting a solid foundation for advanced topics.
Chapter 2: .NET Fundamentals – This section unveils the architecture of the .NET platform, detailing its core components, runtime environment, and the Common Language Runtime (CLR). Readers will learn about .NET’s diverse class libraries, offering a comprehensive view of this powerful platform.
Chapter 3: Basic Concepts of Object-Oriented Programming in C# – Emphasizing the pillars of OOP—encapsulation, inheritance,
polymorphism, and abstraction—this chapter offers a C#-centric view.
Readers will grasp the power of object-oriented design, learning about classes, objects, interfaces, and more.
Chapter 4: SOLID Principles in C# – This chapter demystifies the SOLID principles, laying the foundation for designing robust and
maintainable C# applications. Readers will understand the importance of each principle, from Single Responsibility to Dependency Inversion, and how they guide software craftsmanship.
Chapter 5: Introduction to Design Patterns – A comprehensive introduction awaits as readers embark on a journey to understand the
rationale, significance, and application of design patterns, preparing them to tackle software design challenges with confidence.
Chapter 6: Singleton Pattern in .NET Applications – Exploring the Singleton pattern, this chapter showcases its role in ensuring a class has a single instance, guiding readers through its implementation nuances and real-world applications within the .NET environment.
Chapter 7: Abstract Factory Pattern with Blazor – Diving into the Abstract Factory Pattern, readers will comprehend its importance in
abstracting the creation of related families of objects. The chapter highlights its synergy with the Blazor framework, offering practical insights.
Chapter 8: Prototype Pattern with ASP.NET Razor – This chapter delves into the Prototype Pattern, emphasizing its utility in creating object copies within the context of ASP.NET Razor. Through examples, readers will learn about object cloning and its benefits.
Chapter 9: Factory Method Pattern Using New Features on C# 11 – With a focus on the Factory Method Pattern, readers will explore its
applicability in object creation. Leveraging C# 11’s novel features, the chapter provides an enriched perspective on this creational pattern.
Chapter 10: Adapter Pattern with Entity Framework Core – This chapter illuminates the Adapter Pattern, illustrating its pivotal role in harmonizing incompatible interfaces. Using Entity Framework Core as a backdrop, readers will discover the pattern’s application in real-world scenarios.
Chapter 11: Composite Pattern with ASP.NET MVC – Detailing the Composite Pattern, this section sheds light on managing hierarchies of objects. Within the ASP.NET MVC framework context, readers will grasp its essence and benefits, especially in UI rendering.
Chapter 12: Proxy Pattern with GRPC – The Proxy Pattern takes the spotlight here. Readers will learn its significance in controlling access to objects. The integration with the GRPC framework offers a fresh
perspective on managing object communications.
Chapter 13: Command Pattern Using MediatR – This chapter dissects the Command Pattern, emphasizing its utility in encapsulating request- response mechanisms. With MediatR, readers will experience its potency in decoupling classes and managing operations.
Chapter 14: Strategy Pattern Using Azure C# and Azure Functions – Exploring the Strategy Pattern, this chapter showcases its role in defining interchangeable algorithm families. With C# and Azure Functions as the foundation, readers will learn to dynamically select algorithmic
implementations in cloud-based solutions.
Chapter 15: Observer Pattern – Concluding with the Observer Pattern, readers will delve into the intricacies of maintaining consistency between objects. The chapter highlights the importance of real-time data
synchronization and how the pattern ensures efficient object interactivity and communication.
Code Bundle and Coloured Images
Please follow the link to download the
Code Bundle and the Coloured Images of the book:
https://rebrand.ly/b4af92
The code bundle for the book is also hosted on GitHub at
https://github.com/bpbpublications/Implementing-Design-Patterns-in- C-Sharp-11-and-.NET-7-2nd-Edition. In case there’s an update to the code, it will be updated on the existing GitHub repository.
We have code bundles from our rich catalogue of books and videos available at https://github.com/bpbpublications. Check them out!
Errata
We take immense pride in our work at BPB Publications and follow best practices to ensure the accuracy of our content to provide with an indulging reading experience to our subscribers. Our readers are our mirrors, and we use their inputs to reflect and improve upon human errors, if any, that may have occurred during the publishing processes involved. To let us maintain the quality and help us reach out to any readers who might be having
difficulties due to any unforeseen errors, please write to us at : [email protected]
Your support, suggestions and feedbacks are highly appreciated by the BPB Publications’ Family.
Did you know that BPB offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.bpbonline.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.bpbonline.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 BPB books and eBooks.
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 www.bpbonline.com. We have worked with thousands of developers and tech professionals, just like you, to help them share their insights 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.
Reviews
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 BPB can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about BPB, please visit www.bpbonline.com.
Join our book’s Discord space
Join the book’s Discord Workspace for Latest updates, Offers, Tech
happenings around the world, New Release and Sessions with the Authors:
https://discord.bpbonline.com
Table of Contents
1. C# Fundamentals Introduction Structure Objectives
Tools and Environment Setup Installing Visual Studio 2022
Installing Visual Studio Code Introduction to Visual Studio 2022 Introduction to Visual Studio Code
History of .NET .NET Core Versions
.NET 5, .NET 6 and .NET 7
Introduction to C# Language Loops, Operators, and Iterators
While statement Do-while statement For loop
Foreach statement Operators
Assignment operator Error Handling
Namespaces
New features in C# 10 and 11 Global using directives
Generic Attributes List patterns
Raw string Literals
New Debugger Features in Visual Studio Temporary Breakpoints
Breakpoint hover glyph Conclusion
Points to remember
Multiple Choice Questions Answers
Questions Key terms
2. .NET Fundamentals Introduction
Structure Objectives
Multi-platform concepts .NET for cloud development Azure Storage Accounts
Azure Functions
New features in .NET 6 Hot reload
.NET MAUI HTTP/3
Custom platform checks Conclusion
Points to remember
Multiple choice questions Answers
Questions Key terms
3. Basic Concepts of Object-Oriented Programming in C#
Introduction Structure Objectives
Classes and access modifiers Encapsulation
Inheritance Reusability Polymorphism Partial class Constructor Static classes Structs
Interfaces Conclusion
Points to Remember Multiple choice questions Answer
Questions Key terms
4. SOLID Principles in C#
Introduction Structure Objectives
The Single Responsibility Principle
The open-closed principle
The Liskov substitution principle The interface segregation principle The dependency inversion principle Conclusion
Points to remember
Multiple choice questions Answers
Questions Key terms
5. Introduction to Design Patterns Introduction
Structure Objectives
Importance of design patterns History of Design Patterns Design Pattern categories Creational patterns
Behavioral patterns Structural patterns
Patterns for Distributed Systems Microservices design patterns
Conclusion
Points to remember
Multiple choice questions Answers
Questions Key terms
6. Singleton Pattern in .NET Applications Introduction
Structure Objectives
Single pattern definition Single attern definition Multiple instances
Modifications for the single pattern Thread-safe implementation Dependency injection
Conclusion
Points to remember
Multiple choice questions Answer
Questions Key terms
7. Abstract Factory Pattern with Blazor Introduction
Structure Objectives
Abstract Factory definition Abstract Factory scenario
Abstract Factory implementation Conclusion
Points to remember
Multiple choice questions Answer
Questions
Key terms
8. Prototype Pattern with ASP.NET Razor Introduction
Structure Objectives
Prototype pattern definition
Prototype pattern implementation Conclusion
Points to remember
Multiple choice questions Answer
Questions Key terms
9. Factory Method Pattern Using New Features on C# 11 Introduction
Structure Objectives
Factory Method definition
Factory Method implementation New features in C# 11
Required fields
UTF-8 string literals
Newlines in string interpolations List patterns
Raw string literals Conclusion
Points to remember
Multiple choice questions
Answer
Questions Key terms
10. Adapter Pattern with Entity Framework Core Introduction
Structure Objectives
Adapter pattern definition
Adapter pattern implementation Conclusion
Points to remember
Multiple choice questions Answers
Questions Key terms
11. Composite Pattern with ASP.NET MVC Introduction
Structure Objectives
Composite pattern definition
Composite pattern implementation Conclusion
Points to remember
Multiple choice questions Answer
Questions Key terms
12. Proxy Pattern with GRPC Introduction
Structure Objectives
Proxy pattern definition Proxy pattern types
Proxy pattern structure
Common use in real projects Proxy pattern implementation Scenario requirements
Practical example
GRPC with Blazor Conclusion
Points to remember
Multiple choice questions Answers
Questions Key terms
13. Command Pattern Using MediatR Introduction
Structure Objectives
Command pattern definition Proxy pattern implementation Extra classes
MediatR and Command Pattern Conclusion
Points to remember
Multiple choice questions Answers
Questions Key terms
14. Strategy Pattern Using Azure C# and Azure Functions Introduction
Structure Objectives
Strategy pattern definition Estrategy pattern structure
Strategy pattern implementation Creating the city strategy class
Strategy pattern and Azure Functions Conclusion
Points to remember
Multiple choice questions Answers
Questions Key terms
15. Observer Pattern Introduction
Structure Objectives
Observer pattern definition
Observer pattern implementation Creating the User class
Creating the Blog Post class
Client application Conclusion
Points to remember
Multiple choice questions Answers
Questions Key terms Index
C HAPTER 1 C# Fundamentals
Introduction
With this chapter, we are starting our journey into design patterns using C# 11.0 and .NET 7, walking through the basic concepts of programming in C#, giving you familiarity with the language, its main operations, and instructions that will help you understand what you need to learn to make progress in the next sections of this book, such as object-oriented programming, design patterns, and .NET platform.
You will learn in this chapter how to create and work with variables, operators, and logical and conditional statements. Additionally, you will have the opportunity to have practical experience in implementing basic programs in C#. Further, you will be able to try the new Debugging Experience provided by Visual Studio 2022.
Getting familiar with the basic concepts of C# will allow you to understand how to apply the complex design patterns in the further chapter in this book. It will help you to build enterprise projects using the .NET platform.
Structure
In this chapter, we will discuss the following topics:
Visual Studio 2022 and Visual Studio Code Installation Instructions Introduction to Visual Studio 2022 and Visual Studio Code
Basic operations in C#
Object Types in C#
Loops and iterations in C#
Error handling in C#
New features introduced in C# 10 and C# 11
Objectives
In this unit, you’ll learn to set up Visual Studio IDE and Visual Studio Code, create C# apps, grasp basic language operations, and employ new features from C# 10 and 11. These skills will provide a strong foundation for proficient C#
programming and development.
Tools and environment setup
To get started with software development in .NET 7 and C# 11, you must install the latest Visual Studio 2022 version, a complete Integrated Development Environment (IDE) for creating, compiling, and building your .NET projects.
Visual Studio is available for Windows and macOS, both available in the
Community Edition for studying purposes. The tool can be downloaded from the official Visual Studio website.
Furthermore, Microsoft has provided the Visual Studio Code, a free, open-source alternative light version of code editor for .NET and C# applications, which is available not only for Windows and macOS but also for various Linux
distributions. Considering this editor is an open-source, extensible project, technical communities, IT professionals, and companies around the globe have created numerous extensions for different languages apart from C# itself.
Therefore, it is a suitable tool for creating cross-platform applications without any compatibility concerns. Visual Studio Code can be downloaded on the official website for free.
Installing Visual Studio 2022
After downloading Visual Studio 2022 from the official website, you must take the following steps for the installation:
1. Make sure your user has the necessary permissions to install the software on the operating system. Double-click the downloaded executable file.
2. Choose the desired workloads to be installed and set up with Visual Studio, including the additional native project templates from the .NET platform.
For the examples of this book, the following workloads must be installed, as seen in Figure 1.1:
ASP.NET and web development Azure Development
Node.js development
Mobile development with .NET .NET desktop development
Universal Windows Platform development
After making this step in the installation, the workload list will be shown as the following result in Figure 1.1:
Figure 1.1: Visual Studio 2022 workloads
3. After choosing the necessary workloads, click on the Install option.
4. Usually, Visual Studio is configured to use the same language and region settings as the operating system. If you want to setup a different one, you can do that in the Language Packs option, where other ones will be available.
Visual Studio was configured to the English language for the examples in this book by default. After finishing the installation, you will be already able to create .NET 7 solutions using all the project type available in Visual Studio that belongs to the workloads specified during installation.
Once Visual Studio 2022 is installed, you do not need to install the latest stable version of the .NET SDK, as it is already a part of the Visual Studio installation.
By default, Visual Studio updates and follows the newest features introduced into .NET, such as library updates, minor and major changes, and new project
templates. However, any new library updates after the initial installation will not automatically apply the upgrades to your existing projects. Each project targets a specific .NET version, and Visual Studio updates and modifies just the IDE, not the existing projects’ configurations.
Installing Visual Studio Code
Visual Studio Code is a cross-platform alternative to Visual Studio IDE, and it is a good option if you want a free, lightweight cross-platform editor for .NET projects.
Many companies, technical communities, and individual contributors have provided extensions that allow us to work with many different programming languages in Visual Studio Code. This light open-source IDE has become one of the most popular code editors used in the market. Furthermore, the editor is available for multiple operating systems, such as macOS,Windows, and multiple Linux distributions.
After downloading the executable from the official Visual Studio website, you must take the following steps to complete the installation:
1. Double-click the downloaded executable file. Ensure your user has the necessary permission in the operating system to install the software.
2. Download the Visual Studio extension for C# and Azure, as seen in the following figure:
Figure 1.2: Visual Studio Code extensions
These are the two extensions that can be used along with the code samples in this book, and Visual Studio Code can be used as an alternative to the Visual Studio 2022 IDE if you would like to use more command lines for .NET applications.
Introduction to Visual Studio 2022
The Visual Studio 2022 is such a powerful IDE for software development, which allows you to create, build, debug and deploy your .NET applications using a single tool with numerous plugins and extensions, giving you a rich user
experience as a developer. It includes the possibility of having access to external resources such as databases and cloud services. In addition, the Visual Studio contains natively installed project templates along with the initial setup, including code samples for Web projects, Desktop, and Mobile applications, which give us a quick way to start a project without having to set up everything from scratch in terms of simple and common configurations. To access those templates, click the
File option on the super menu and choose the New Project option, as seen in Figure 1.3:
Figure 1.3: Visual Studio templates
After installing the most recent Visual Studio version, the most popular project templates for .NET applications become available, according to the workloads chosen during the installation, such as Console App, ASP.NET Core Web API, Blazor App, and much more. Each project template has other sub-types ready to use, a variation of the main template. Those templates are time-saving, speeding up the software development process and helping learner developers understand how each type of project can be structured.
Open-source communities, companies, and individual developers who publish the templates as Visual Studio extensions on the Visual Studio Marketplace website develop and share many extra free templates. Additionally, Visual Studio
extensions for many other purposes can be downloaded on the same website to get a better experience for software development within Visual Studio, getting
integrations with third-party tools.
After creating any simple project, the template list available in Visual Studio, you are redirected to the Solution Explorer experience, having in a common place the code editor, access to the files and folder structure for your project, and access to any relevant external resources, as seen in Figure 1.4:
Figure 1.4: Visual Studio Code editor área
On the Solution Explorer sidebar, you can access all the existing folders in files of your projects, including all the resources related to all the linked projects if you have multiple projects in the same solution. Furthermore, this Solution Explorer
view allows you to have access to extra options for the configuration of your projects, such as the installation of extra packages, third-party libraries, and other resources available through Nuget Packages and project references by right- clicking on an individual project in the solution and choosing the Manage NuGet Packages option, as seen in Figure 1.5:
Figure 1.5: Manage NuGet Packages option
After choosing the underlying Manage Nuget Packages option, a new window is available where it is possible to search and install any published Nuget packages, specifying the desired version, as seen in Figure 1.6:
Figure 1.6: Nuget Packages window
Another exciting option is to install packages using the commandline, which makes the process much easier and faster once the developer has enough familiarity with the available commands. Under the Nuget Packages Console window, which appears at the bottom of Visual Studio, it is possible to use the
dotnet install command, followed by the name of the package, as seen in Figure 1.7:
Figure 1.7: Dotnet CLI for Nuget Packages
Continuing the Visual Studio coding area presented in Figure 1.4, the Editor sidebar is where you develop your code. It can get tips by Visual Studio on code syntax, indentation, codification error messages, navigating into classes, functions and functions and methods, including project references within the source code.
The editor has a high level of customization, meaning many settings can be changed to adjust according to your needs. This customization involves background color, contrast level, font size, and more.
Finally, on the Server Explorer sidebar shown in Figure 1.4, it is possible to connect to external resources, including databases, application servers, cloud infrastructure, and on-premise features. With all the integrated features in Visual Studio, you can keep all the work in a single and shared place, which has an
excellent value for high productivity. In the select Toolbar, there is an option to run applications, save pending changes, hot reload, debug capabilities, comment
features, options to undo recent changes, and much more, as seen in Figure 1.8:
Figure 1.8: Visual Studio Toolbar
The .NET platform allows us to build applications using C#, Vb.Net, and F#
languages. F# is a programming language based on the functional programming paradigm, and the Vb.NET is a programming language largely used in .NET projects since the beginning of the platform, despite the fact the C# language has taken over the preference of .NET developers in general to build .NET enterprise applications. Within Visual Studio, under the project creation dialog, you can choose the language for your project by choosing the correct and corresponding project template, as seen in Figure 1.9:
Figure 1.9: Visual Studio templates for F# language
Given the example in Figure 1.9, the Visual Studio shows all the available project templates based on the F# language. Therefore, there are alternatives to the C#
language within the .NET platform, including the possibility of multiple projects in the same solution, each targeting a different programming language as the core language.
Visual Studio is a complete IDE for .NET applications. It does not require the installation of extra tools to build and execute standard programs based on C# or any other language supported by .NET.
Introduction to Visual Studio Code
At first glance, Visual Studio Code seems quite different from Visual Studio 2022 in terms of user experience. Still, both have the same purposes: to create, debug, build and deploy applications using the .NET platform or other platforms. At its core, this light IDE contains many extensions to make our routine as developers easier and more productive. It is certain to say that the main difference between Visual Studio Code and Visual Studio 2022 is the cross-platform capabilities for
development once the first one is available for Linux, Windows, and macOS operating systems. Still,Visual Studio is available only for Windows and macOS, with limited capabilities in the macOS version. On the other hand, you must install and enable each extension and extra component on Visual Studio Code to get everything you need to develop specific applications. In terms of comparison with other Visual Studio versions, the Figure 1.10 shows that the options available for Visual Studio Code are pretty similar to the ones present in Visual Studio 2022:
Figure 1.10: Visual Studio Code editor áreas
On the Explorer sidebar, you can access all the existing folders and files of your projects, including the possibility of managing multiple and simultaneous projects in various windows in the same Explorer. As seen in Figure 1.10, the Editor
sidebar is where you develop the actual code and can get a similar experience as Visual Studio regarding code tips, snippets, and much more.
Visual Studio Code is a command-line-based editor, meaning it may have fewer visual options in the IDE to manage and develop your projects. However, you can benefit from quickly running, building, and creating new files for your application using commands without having to use the mouseclicks for it, increasing
productivity if you are familiar with the commands and shortcuts available.
The traditional complete Visual Studio 2022 IDE version relies on the existing specification within .sln (solution) files and specific extensions for projects, such as .csproj files for C# projects, to open the project solutions correctly. Although, Visual Studio Code allows you to run code by only opening simple folders and files, which is useful in case you want to run other languages that are not .NET related in the same Visual Studio Code simultaneously.
Speaking of productivity and menu options, Visual Studio Code is more flexible and customizable than Visual Studio, as it contains many predefined commands and shortcuts to get files, a more friendly search option across folders and files, and much more, as seen in Figure 1.11:
Figure 1.11: Visual Studio Code shortcuts
Visual Studio is the most popular code editor in the market right now. The features available are increasing exponentially over time because of the intense
contributions by active technical communities behind this project, providing a lot of extensions and new capabilities.
History of .NET
The .NET platform was created long before Web applications became popular and even before the first C# language. Despite the massive adoption of .NET these days, there is a first impression that the scenario in the market was always like the current state, especially for those who did not experience software development around the beginning of the 1990s. Looking back at almost three decades ago, when other programming languages were prevalent like Java and PHP at this time, it seemed essential for Microsoft to enter this great market of development tools for enterprise applications. In this context, the first version of the .NET platform was launched as a beta product in 2000. In February of 2022, the official 1.0 version was finally released, supporting Windows 98, Millennium, and XP.
The most important feature of this first version was the Common Language Runtime (CLR) capability, which allowed developers to create .NET applications using more than one programming language within the same solution. The .NET platform was able to execute the multiple projects in runtime using CLR,
converting the output for each programming language into Common Intermediate Language (CIL), also called Intermediate Language (IL), therefore giving the possibility of sharing libraries written in C# and libraries written in Visual Basic for a single application, increasing the capabilities in terms of reusability. This ability to use multiple programming languages to develop a single application did not necessarily mean that it was possible to create multi- platform applications using .NET at this time. In contrast, running and developing a .NET application only on Windows OS was possible.
In the second quarter of 2003, the first relevant major version of .NET was released under the .NET 1.1 version, and the support for Open Database Connectivity (ODBC) was introduced at this stage, following standard
requirements for database integrations in .NET applications. Up to this point, .NET did not have wide adoption in the market, and important features should be
released to meet the most modern software development demands and trends of this specific time.
In January 2006, Microsoft launched the .NET Framework 2.0 and other relevant tools and products, such as Visual Studio 2005, a more stable release of the new SQL Server 2005, and Biz Talk. One of the most significant achievements of this version was the support of 64-bits computer architecture and new features in C#
language, such as partial class, new authentication options for ASP.NET, and Datatable objects, which allowed the management of database operations using in- memory databases.
Alongside these new features, Visual Studio was becoming mature and complete for enterprise applications development, being a full IDE, even for programmers who had expertise with other programming languages that .NET did not have support at the time. Additionally, the ASP.NET Web Forms project started having an extensive adoption among developers who had experience with Desktop
development, having a large migration of professionals to Web development.
Visual Studio 2005 already contained features to facilitate the creation of visual Web components, allowing dragging and dropping visual Web components on the screen, to build Web pages with similar experience developers had with Desktop development.
ASP.NET Web Forms occupied an essential space in the .NET Framework before the existence of the ASP.NET Model View Controller (MVC) project was
introduced to the platform. Web page navigation based on forms was common at the beginning of the Web. It essentially considered a user sending requests from the Web browser, and the server returns a response, always keeping the state of the entire page, including all the Web controls, on the server. In this model, the server
was responsible for processing the HTML and related content, including dynamic data. This approach used the View State model to store the values of all server-side components between each request. Additionally, ASP.NET Web Forms provided the option to use separated files between HTML and the logical code for each page, which was considered an innovation at this time.
In November of 2006, .NET Framework 3.0 was released, including new features related to Desktop development and Web Services. The JavaScript Object
Notation (JSON) pattern was not used for integrating services at this time. The Extensible Markup Language (XML) was the most used alternative for standard communication between systems. The Windows Communication Foundation (WCF) from the .NET platform became the official Web Service of .NET. The WCF became obsolete overtime once .NET replaced it with the Web Application Programming Interface (API) model, following the most modern pattern adopted in the market after 2006.
One of the benefits of WCF was its integration with native Visual Studio tools, which allowed developers to import third-party endpoints from other Web Services into Visual Studio by informing the Web Service URL, generating the underlying C# classes for the corresponding objects specified in external services, even the services were written using other programming languages. This helper was focused on interpreting the XML specification on the third-party Web Service to create the corresponding objects and their properties without being necessary to write any line of code. Additionally, the Service Import tool automatically generated the methods in C# language to establish a connection with the referenced Web Service, allowing to send requests to the service following the underlying service
specification and parsing the service response to a format the C# classes would understand. It represented a productive tool at the time and was a key point for WCF to become so popular in the market combined with other .NET tools.
These days, many companies still have Web Services developed using the WCF specification for legacy projects. The same situation happens for ASP.NET Web Forms applications, as many companies adopted it to large and complex projects and have not migrated them yet to a new version of Web projects based on .NET.
Another important technology introduced to .NET Framework 3.0 was the Windows Presentation Foundation (WPF) project type, a new way to create Desktop applications using the Extensible Application Markup Language (XAML) to develop rich user interfaces using 3D computer graphics capabilities.
This type of project represented an alternative to the traditional Windows Form project type existing in the .NET platform.
When the .NET Framework 3.5 was released in November of 2007, it brought performance improvements for Desktop applications. It introduced the first version of Entity Framework, giving the possibility of improving the experience for
developers to communicate applications with relational databases, representing an alternative to the Object-Relational Mapping (ORM) frameworks that became popular on other platforms. However, a new release of Entity Framework had to be launched in 2008 at the same time as the .NET Framework Service Pack 1,
including relevant updates after technical community feedback, with this version not being mature enough to be mainly by a relevant number of companies and projects worldwide. The ORM concept and its importance were widely accepted on the market, and huge improvements to Entity Framework became extremely necessary, mainly to give reliability and stability to the tool.
After only one year of the Entity Framework updates, Microsoft provided version 4.0 of the .NET Framework. Still, it did not present any break changes to previous versions and did not have many new features as part of the update. Differently, the .NET Framework 4.5, released in August of 2012, contained many improvements for Web applications, Desktop development, and native components for Windows 8. Among all the new features in this version, the new capabilities for the
ASP.NET application stood out, including support for HTML 5 for Web Forms and support for Websocket protocol, representing a large step to follow the most
modern Web standard practices at that point. Additionally, this .NET version allowed the use of asynchronous HTTP requests and responses.
In July 2015, the .NET Framework 4.6 was launched, being the last big version of the framework before it became multi-platform with .NET Core, although it still has minor updates in the versions 4.7 and 4.8. The 4.6 version introduced the
support for Azure SQL Server distributed transactions, improvements related to the WPF user interface, and support for data localization using annotation attributes for ASP.NET applications.
.NET Core versions
Considering the existing scenario back in 2015, the market for software
development was changing to become compatible with cross-platform concepts. In this context, the fact that the .NET platform had support only for Windows
operating systems represented a significant limitation for its evolution and
influence in the market. In 2005, it was largely accepted by companies, developers, and technical communities that cross-platform development was something
mandatory for the success and costs of any software project, with the capability for the underlying technologies involved in the software development process to be
executed in multiple operating systems, multiple types of devices, and to have interoperability with other technologies and platforms.
Focused on meeting these new requirements, Microsoft launched in June of 2016 the first version of .NET Core. This disruptive platform allows the development, deployment, and execution of .NET applications on Linux and macOS. The .NET libraries and packages for C# and Visual Basic languages were completely re- written from scratch, and a new version of ASP.NET projects and Entity
Framework were created as well, with these products being renamed to ASP.NET Core and Entity Framework Core, following the new brand of .NET for cross- platform development.
Additionally, all the .NET Core libraries and their projects became open-source projects, with the code being shared on Github, making it possible for anyone in the technical community to contribute and collaborate to the evolution of the subsequent releases, reporting issues on features and giving feedback on new capabilities within the platform on various projects. The change to an open-source model represented a big milestone for .NET developers, as only the ASP.NET MVC project could be considered an open-source project at this point. It
significantly contributed to .NET adoption by developers from other technologies.
.NET Core 1.1 was released in November of 2016, containing many solutions for issues reported by developers and companies, and focused on supporting a more comprehensiverange of Linux distributions. Additionally, this version improved the Entity Framework tool to support Azure and SQL 2016.
In August of 2017, .NET Core 2.0 was launched, with the possibility to integrate with legacy .NET Framework libraries using .NET Standard as middleware, improving cross-platform support with new features. The version brought the new Razor Pages Web project, an alternative to the traditional ASP.NET MVC project type for creating Web applications within the .NET Core platform. At this point, .NET Core became a mature platform, primarily adopted by companies worldwide.
The support for cross-platform development was the key of .NET Core, joined with Visual Studio Code and new command-line options. Developers were able to create .NET applications that could be executed almost everywhere, taking part in the evolution of the next version of .NET with incremental solid updates via open- source projects, also taking the benefits of performance improvements across many .NET libraries.
The .NET Standard mentioned previously in this chapter was a typical API specification for .NET libraries that allows us to use it across all .NET projects, regardless of its version. This means that different types of projects could share
libraries with the .NET Standard, including compatibilities between a wide range of .NET Framework and .NET Core libraries. It is essential to mention that .NET Core and .NET Standard are different things. The first one is not directly
compatible with .NET Framework libraries, and the second one was made to be a bridge between all .NET versions. Therefore, the best strategy to migrate .NET Framework applications to .NET Core is to create libraries in .NET Standard. In that way, it is possible to keep the implementation of legacy projects without any significant breaking changes and use the same libraries in .NET Core projects to transition to a new version of .NET gradually.
As you can see in Figure 1.12, .NET Standard represents the intersection between .NET Framework and .NET Core libraries, keeping high-level compatibility in the version 2.0, reaching a good point of maturity:
Figure 1.12: .NET Standard
Each new version of the .NET Standard added universal compatibility for .NET projects, including .NET Core, .NET Framework, Mono, Xamarin, and Unit. .NET Standard represents a base specification for any library across the entire .NET ecosystem, including Mobile, Desktop, Web and Game development. The .NET Standard 2.0 supports interoperability with .NET Framework 4.6.1 or later
versions. Therefore, projects using an older version of the .NET Framework would not be able to use .NET Standard libraries target the 2.0 version. In that case, it is recommended to migrate legacy projects to .NET Framework 4.6.1 before starting any migration to .NET Core.
Since the first version, .NET Core had many improvements and significant new features, with the cross-platform capabilities being strictly followed in all the versions, including the .NET Core 3.0 version, being a game-changer in terms of compliance with the requirements of modern software development as it supports
Windows Forms, WPF, Artificial Intelligence (AI), and Internet of Things (IoT).
In the following chapters of this book, you will have the opportunity to dive deeply into all these types of projects and understand the performance improvements that were applied to .NET Core, .NET 5, .NET 6, and .NET 7.
.NET 5, .NET 6 and .NET 7
In November 2020, Microsoft released the .NET 5, which represented the
beginning of a new era in software development using the .NET platform once all the effort for cross-platform development reached a good level of maturity and stability. This means that the most relevant .NET libraries were fully migrated to have cross-platform compatibility at this point.
Among all .NET versions, .NET 5 represents an evolution of .NET Core 3.1 and .NET Framework 4.8, a massive milestone in consolidating all the effort regarding cross-platform development that started in the .NET platform since .NET Core 1.0.
Therefore, it is possible to say that .NET 5 is a unification of the .NET ecosystem for modern and cross-platform development, combining new features and relevant performance improvements.
The unified platform has the cross-platform focus as a key point, which does not only mean compatibility across multiple operating systems, but in terms of multiple devices and platforms, such as Desktop, Web, Cloud, Gaming, IoT, and others. The achievement of multi-platform development using .NET required a complex re-architecture of the entire .NET platform, bringing at the same time significant improvements in terms of performance for existing features for C#
language, including type conversions, parallelization, and much more.
In November of 2021, the .NET 6 was launched by Microsoft, which included further performance improvements, Arm64 support, .NET MAUI, C# 10, new project templates, support for HTTP/3, improvements on code analysis, DateTime and timezone improvements, and much more. At this point, many companies were already using .NET 5, and the migration to .NET 5 did not represent a huge
challenge for legacy projects.
Finally, in November of 2022, .NET 7 will bring significant improvements for modern client development with .NET MAUI, Cloud Native improvements, and new tools to upgrade existing .NET applications.
Introduction to C# language
The best way to learn any programming language is to create real applications for practicing and apply the technical knowledge regarding the most basic concepts of coding in real scenarios. First, basic concepts apply to any programming language, such as variables, loops, blocks, and iterators. In the following sections of this chapter, you will have the opportunity to experience and create multiple C#
applications, having exposure to most concepts of the language.
C# is a strong-typed language requiring all the variables specified with a specific type. Therefore, if a variable is created to store only numbers, any attempt to store any other type of content results in an error in compile time. In computer
programming, there are also weakly typed languages, which are not pre-compiled, with the variable types being checked dynamically once the application runs. As a strong-typed language, C# language makes it mandatory to specify any variable type in the source code, explicitly indicating what type of data should be stored on each variable.
A variable in a programming language could store simple data structures, such as numbers, strings, and Boolean values. Still, it also could store more complex data that represent custom objects, such as generic list types, structs, arrays, instances of classes, and much more. The correct use of variable types represents an essential aspect of software development in terms of good practices considering they are closely related to the application’s state and how it interacts and handles memory and other computer resources. Sometimes, mistakes made on variable
specifications may represent a security vulnerability.
In terms of code readability, it is essential to use a good naming convention for variables and any custom implementation during software development. Always use meaningful names for variables, methods, classes, functions, projects, and structs. In C# language, the camel case pattern for classes is primarily used (for example, MyBook) and the upper case for constants (for example, MAX_ITEMS_ORDER).
Make your code easy to read by others and even by yourself. It increases productivity, reduces project costs, and boosts collaboration in software development teams.
Figure 1.13 represents a simple creation and value assignment for a C# variable within a Console application:
Figure 1.13: C# variables
Lines 3 and 4 represent two different variables created using different types. The first one uses the string type, which stores the content “I’m reading the Design Patterns with .NET book.” Considering that it is a string value, the content must be around quotes, as that is the pattern for any string in the C# language. For the second variable in the code sample (line 4), a double type was specified, which stores a decimal value (7.0) and does not require using quotes as it is a number value. The variable should be named according to its purpose, and it can be used in other of the program within the same scope: class, method, or a local function.
There are many variables in the C# language, and each has a specific reason to be used. The following list contains the most popular types and their detailed
explanation with examples:
object: It is the most basic type in C# language because all the other types are derived from it. This type allows us to assign values of any type as a generic type, primarily used for dynamic types, mainly in cases where the variable’s target value is unknown.
int: This type was created to store integer numbers, positive or negative.
Similar to any other variable type, there are limits in terms of size established for integers (maximum and minimum values) that can be stored.
In that case, the minimum value for integer in C# language is -2,147,483,648, and the maximum value is 2,147,483,647. This limitation helps to prevent memory leaks and security vulnerabilities. Each time a variable is created in the program, a space is reserved in the memory to store the value and keep the reference in the memory for reference types. For this reason, choosing the suitable variable type for any variable used in the application is highly recommended. Furthermore, it is possible to use integer types with other sizes in the C# language. For instance, the short type allows us to store a number between -23,768 and 32, 767 (System.Int16), the long type allows us to store an integer between 223,372,036,854,775,808 and 9,223,372,036,854,775,807 (System.Int64), and there are many more
options. The correct integer type to use in a specific program depends directly on the requirements of the data in terms of precision and size.
Usually, the int type is used in most cases if there is no explicit requirement determining another type, with this type representing a 32-bit number (System.Int32).
boolean: This variable type has the purpose of storing logical content that represents a true or false value, as shown in Figure 1.14:
Figure 1.14: C# bool variables
Line 9 represents a bool variable string, a true value, and line 10 prints the value for the underlying value on the console.
string: As shown in Figure 1.8, the string type has the purpose of string a sequence of Unicode characters and requires the use of quotes around the value. The correct syntax for the string type indicates to the compiler that the content is effectively a string content. Additionally, it is possible to use the String class as an alternative to achieve similar results. Both contain similar properties, but considering the String type, with a capital letter, is a complex type, it will be handled differently on the memory in a less efficient way in specific scenarios that requires a structure use of computational resources and relevant scale workload. Each primitive type in C# language has its corresponding class under the System namespace: System.String,
System.Int32 and many others.
byte: It is a type used for storing unsigned integer values that start with “0”
(minimum value) and “255” (maximum value). It is commonly used to manipulate file bytes in arrays of that type (byte) and low-level programming.
char: This type stores a single Unicode character, unlike the string type that stores a sequence of those values. The utilization of this type is especially useful to allocate less space in the memory if the content is just a simple Unicode character. If the quantity of characters in a variable is predefined and predictably a Unicode character, choose this type of variable instead of string type.
float: This is used to store numbers with precision between 6 and 9 digits, having a maximum size of just 4 bytes.
decimal: This type is used to store numbers with precision between 28 and 29 digits, and the maximum size is 16 bytes.
Each type is suitable for a specific type of data. For example, the decimal type is primarily used to store financial information, as seen in Figure 1.15:
Figure 1.15: Type examples
All the variable types shown in this chapter can be considered primitive types in C# language, as they represent the simplest structure in a program to store data.
Each type has its limitation in terms of size and allocation in the memory once the variable is created. The .NET garbage collector feature cleans them up from the memory once they are not used to keep only the necessary information on the memory and to have high-performance memory management.
If an incorrect value type is assigned to a variable, the compiler shows an error, preventing the program from running. This type-check in compile-time represents a huge advantage in favor of the use of strongly typed language like C# because this feature allows us to figure out programming issues earlier than other languages that accept only dynamic types, which values are verified in runtime.
In C# language, there are differences between value type and reference type variables. The primitive types (int, string, bool, and so on) are considered value types once their value is stored in their own memory space. On the other hand, the reference type has a reference placed in the memory for the variable, and its
underlying value is placed in different memory spaces. Being familiar with these differences is essential when a scenario requires the development of a high-demand system and requires high performance.
Although string and object types are considered primitive types, they can also be considered reference types in C# language alongside classes, interfaces, and
delegate types. Therefore, there is no mandatory relation between value types and primitive types.
The following topics contain the most popular native reference types and their detailed explanation with examples:
Array: This type has the purpose of storing a collection of objects, allowing to specify multiple values in a single variable, optimizing time in the manipulation of a huge amount of values using multiple distinct variables.
To create an array, you must declare the variable type followed by square brackets, and the values can be assigned separated by a comma. As seen in Figure 1.16, you can use any available iteration resource in C# (while,
foreach, and for) to loop through each value of the array:
Figure 1.16: Array in C#
List: It is a complex object that allows us to manipulate elements as a list and access those values by index. This type contains many extension methods to search elements on the list, sorting, and making various operations. This is one of the most used types in C# because almost all the programs have a common need to manipulate lists of elements that come from databases and other sources. When a list is created, the type of elements should be defined already, and the values can be assigned using the
Add method, which is part of the List class. This type supports a wide variety of operations, the main difference between that type and array variables.