C# Data Structures and Algorithms: Harness the power of C# to build a diverse range of efficient applications
By Marcin Jamro
()
Marcin Jamro
Marcin Jamro, PhD, DSc (dr hab. inż. Marcin Jamro) is a reliable entrepreneur, a helpful expert, and an experienced developer, with significant international experience. He held the role of CEO at a few technological companies, operated as CTO at companies in various countries, and also worked at Microsoft Corporation in Redmond, USA. Marcin shares his knowledge as an expert in international projects and invests in modern solutions. He is the author of a few books on software engineering, as well as the author of numerous publications. The results of his research were presented and discussed at many scientific conferences. He has MCPD, MCTS, MCP, and CAE certificates. Marcin is a multiple laureate, finalist, and mentor in various competitions. He received the Primus Inter Pares medal and also, a few times, a scholarship for the Minister of Science and Higher Education for scientific achievements. Marcin has significant experience in project development, especially with the C# language and .NET-based technologies. He has performed the role of lead architect on numerous complex software projects, including web and mobile applications, APIs, databases, and integration with external components.
Related to C# Data Structures and Algorithms
Related ebooks
C# Data Structures Explained: A Practical Guide with Examples Rating: 0 out of 5 stars0 ratingsData Structures Explained: A Practical Guide with Examples Rating: 0 out of 5 stars0 ratingsIntroduction to Algorithms & Data Structures: Learn Linear Data Structures with Videos & Interview Questions Rating: 0 out of 5 stars0 ratingsData Structure and Algorithms in Java: From Basics to Expert Proficiency Rating: 0 out of 5 stars0 ratingsCoding Basics with Microsoft Visual Studio: A Step-by-Step Guide to Microsoft Cloud Services Rating: 0 out of 5 stars0 ratingsMastering Algorithms and Data Structures Rating: 0 out of 5 stars0 ratingsJava Programming: Algorithms and Structures Rating: 0 out of 5 stars0 ratingsC# Algorithms for New Programmers: A Practical Guide with Examples Rating: 0 out of 5 stars0 ratingsMastering Data Structures and Algorithms in Python & Java Rating: 0 out of 5 stars0 ratingsC Data Structures and Algorithms: Implementing Efficient ADTs Rating: 0 out of 5 stars0 ratingsMastering Data Structures and Algorithms with Python: Unlock the Secrets of Expert-Level Skills Rating: 0 out of 5 stars0 ratingsIntroduction to Algorithms & Data Structures: A solid foundation for the real world of machine learning and data analytics Rating: 0 out of 5 stars0 ratingsAdvanced Java Data Structures: Techniques and Applications for Efficient Programming Rating: 0 out of 5 stars0 ratingsData Structure in Python: From Basics to Expert Proficiency Rating: 0 out of 5 stars0 ratingsData Structures and Algorithms with Python Rating: 0 out of 5 stars0 ratingsPython Data Structures and Algorithms Rating: 5 out of 5 stars5/5Basic Concepts in Data Structures Rating: 0 out of 5 stars0 ratingsJavaScript Data Structures Explained: A Practical Guide with Examples Rating: 0 out of 5 stars0 ratingsData Structures and Algorithm Analysis in Java, Third Edition Rating: 4 out of 5 stars4/5Mastering Data Structures and Algorithms in C and C++ Rating: 0 out of 5 stars0 ratingsC# OOP Step by Step: A Practical Guide with Examples Rating: 0 out of 5 stars0 ratingsC# Interview Guide: Boost your confidence with answers to hundreds of secret interview questions Rating: 0 out of 5 stars0 ratingsProgramming Problems: A Primer for The Technical Interview Rating: 4 out of 5 stars4/5Data Structures and Algorithms with the C++ STL: A guide for modern C++ practitioners Rating: 0 out of 5 stars0 ratingsC++ Advanced Programming: Building High-Performance Applications Rating: 0 out of 5 stars0 ratingsC# Fundamentals Made Simple: A Practical Guide with Examples Rating: 0 out of 5 stars0 ratingsC# Essentials for New Coders: A Practical Guide with Examples Rating: 0 out of 5 stars0 ratingsCrushing The Technical Interview: Data Structures And Algorithms (Python Edition) Rating: 0 out of 5 stars0 ratingsAlgorithms and Data Structures: An Easy Guide to Programming Skills Rating: 0 out of 5 stars0 ratings
Programming For You
Python: Learn Python in 24 Hours Rating: 4 out of 5 stars4/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5Linux: Learn in 24 Hours Rating: 5 out of 5 stars5/5Microsoft Azure For Dummies Rating: 0 out of 5 stars0 ratingsLearn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5Excel 101: A Beginner's & Intermediate's Guide for Mastering the Quintessence of Microsoft Excel (2010-2019 & 365) in no time! Rating: 0 out of 5 stars0 ratingsBeginning Programming with C++ For Dummies Rating: 4 out of 5 stars4/5C All-in-One Desk Reference For Dummies Rating: 5 out of 5 stars5/5Learn NodeJS in 1 Day: Complete Node JS Guide with Examples Rating: 3 out of 5 stars3/5Python Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5JavaScript All-in-One For Dummies Rating: 5 out of 5 stars5/5Learn SQL in 24 Hours Rating: 5 out of 5 stars5/5The 1 Page Python Book Rating: 2 out of 5 stars2/5Beginning Programming with Python For Dummies Rating: 3 out of 5 stars3/5Hacking Electronics: Learning Electronics with Arduino and Raspberry Pi, Second Edition Rating: 0 out of 5 stars0 ratingsPython Data Structures and Algorithms Rating: 5 out of 5 stars5/5Python for Data Science For Dummies Rating: 0 out of 5 stars0 ratings
Reviews for C# Data Structures and Algorithms
0 ratings0 reviews
Book preview
C# Data Structures and Algorithms - Marcin Jamro
C# Data Structures and Algorithms
Copyright © 2024 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 author, 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.
Group Product Manager: Kunal Sawant
Publishing Product Manager: Teny Thomas
Book Project Manager: Manisha Singh
Senior Editor: Nithya Sadanandan
Technical Editor: Rajdeep Chakraborty
Copy Editor: Safis Editing
Indexer: Rekha Nair
Production Designer: Gokul Raj S.T
DevRel Marketing Coordinator: Shrinidhi Manoharan
Business Development Executive: Kriti Sharma
First published: April 2018
Second edition: February 2024
Production reference:1290124
Published by
Packt Publishing Ltd.
Grosvenor House
11 St Paul’s Square
Birmingham
B3 1RB, UK
ISBN 978-1-80324-827-1
www.packtpub.com
Contributors
About the author
Marcin Jamro, PhD, DSc (dr hab. inż. Marcin Jamro) is a reliable entrepreneur, a helpful expert, and an experienced developer, with significant international experience. He held the role of CEO at a few technological companies, operated as CTO at companies in various countries, and also worked at Microsoft Corporation in Redmond, USA. Marcin shares his knowledge as an expert in international projects and invests in modern solutions.
He is the author of a few books on software engineering, as well as the author of numerous publications. The results of his research were presented and discussed at many scientific conferences. He has MCPD, MCTS, MCP, and CAE certificates. Marcin is a multiple laureate, finalist, and mentor in various competitions. He received the Primus Inter Pares medal and also, a few times, a scholarship of the Minister of Science and Higher Education for scientific achievements.
Marcin has significant experience in project development, especially with the C# language and .NET-based technologies. He has performed the role of lead architect on numerous complex software projects, including web and mobile applications, APIs, databases, and integration with external components.
You can learn more about the author at his website: https://marcin.com
.
About the reviewer
Alexej Sommer is a professional software developer and technology enthusiast with expertise in a variety of technologies, mainly .NET and Azure. He is MCP/MCSD/Azure Developer/PSM I-certified.
Alexej is a former Microsoft Student Partner and Most Valuable Professional in the Windows Development category.
Currently, he occasionally participates as a speaker at IT conferences and meetups.
Table of Contents
Preface
1
Data Types
C# as a programming language
.NET-based console applications
Division of data types
Value types
Integral numbers
Floating-point numbers
Boolean values
Unicode characters
Constants
Enumerations
Value tuples
User-defined structs
Nullable value types
Reference types
Objects
Strings
Classes
Records
Interfaces
Delegates
Dynamics
Nullable reference types
Summary
2
Introduction to Algorithms
What are algorithms?
Definition
Real-world examples
Notations for algorithm representation
Natural language
Flowchart
Pseudocode
Programming language
Types of algorithms
Recursive algorithms
Divide and conquer algorithms
Back-tracking algorithms
Greedy algorithms
Heuristic algorithms
Dynamic programming
Brute-force algorithms
Computational complexity
Time complexity
Space complexity
Summary
3
Arrays and Sorting
Single-dimensional arrays
Example – month names
Multi-dimensional arrays
Example – multiplication table
Example – game map
Jagged arrays
Example – yearly transport plan
Sorting algorithms
Selection sort
Insertion sort
Bubble sort
Merge sort
Shell sort
Quicksort
Heap sort
Performance analysis
Summary
4
Variants of Lists
Simple lists
Array lists
Generic lists
Sorted lists
Example – address book
Linked lists
Singly linked lists
Doubly linked lists
Circular singly linked lists
Circular doubly linked lists
List-related interfaces
Summary
5
Stacks and Queues
Stacks
Example – reversing a word
Example – Tower of Hanoi
Queues
Example – call center with a single consultant
Example – call center with many consultants
Priority queues
Example – call center with priority support
Circular queues
Example – gravity roller coaster
Summary
6
Dictionaries and Sets
Hash tables
Example – phone book
Dictionaries
Example – product location
Example – user details
Sorted dictionaries
Example – encyclopedia
Hash sets
Example – coupons
Example – swimming pools
Sorted
sets
Example – removing duplicates
Summary
7
Variants of Trees
Basic trees
Implementation
Example – hierarchy of identifiers
Example – company structure
Binary trees
Traversal
Implementation
Example – simple quiz
Binary search trees
Implementation
Example – BST visualization
Self-balancing trees
AVL trees
Red-black trees
Tries
Implementation
Example – autocomplete
Heaps
Summary
8
Exploring Graphs
The concept of graphs
Applications
Representations
Adjacency list
Adjacency matrix
Implementation
Node
Edge
Graph
Example – undirected and unweighted edges
Example – directed and weighted edges
Traversal
Depth-first search
Breadth-first search
Minimum spanning tree
Kruskal’s algorithm
Prim’s algorithm
Example – telecommunication cable
Coloring
Example – voivodeship map
Shortest path
Example – path in game
Summary
9
See in Action
The Fibonacci series
Minimum coin change
Closest pair of points
Fractal generation
Rat in a maze
A Sudoku puzzle
Title guess
A password guess
Summary
10
Conclusion
Classification
Arrays
Lists
Stacks
Queues
Dictionaries
Sets
Trees
Graphs
The last word
Index
Other Books You May Enjoy
Preface
Hello, I am Marcin!
It is so nice to meet you and to invite you to an amazing journey through various data structures and algorithms presented in this book. As you could already know, developing applications is certainly something exciting to work on, but it is also challenging, especially if you need to solve some complex problems. In such cases, you often need to take care of performance to ensure that the solution will work smoothly on devices with limited resources. Such a task could be really difficult and could require significant knowledge regarding not only the programming language but also data structures and algorithms. However, have you ever thought profoundly about them and their impact on the performance of your applications? If not, it is high time to take a look at this topic, and this book is a great place to start!
Did you know that replacing even one data structure with another could cause the performance results to increase hundreds of times or even more? Does it sound impossible? Maybe, but it is true! As an example, I would like to tell you a short story about one of the projects in which I was involved some time ago. The aim was to optimize the algorithm to find connections between blocks on a graphical diagram. Such connections should be automatically recalculated, refreshed, and redrawn as soon as any block has moved in the diagram. Of course, connections cannot go through blocks and cannot overlap other lines, and the number of crossings and direction changes should be limited. Depending on the size and the complexity of the diagram, the performance results differ significantly. However, while conducting tests, we received results in the range of 1 ms to almost 800 ms for the same test case. What was perhaps the most surprising aspect is that such a huge improvement was reached mainly by... changing the data structures of two sets.
Are you interested in knowing the influence of choosing a suitable data structure on the performance of your application? Do you want to know how you can increase the quality and performance of your solution by choosing the right accompanying algorithm? Are you curious about real-world scenarios where various data structures can be applied, as well as which algorithms could be used to solve some common problems? Unfortunately, the answer to such questions is not simple. However, within this book, you will find a lot of information about data structures and algorithms, presented in the context of the C# programming language, with many examples, code snippets, illustrations, and detailed explanations. Such content could help you to answer the aforementioned questions while developing the next great solutions, which could be used by many people all over the world! Are you ready to start your adventure with data structures and algorithms? If so, welcome on board of this book!
The book covers many data structures, starting with simple ones, namely arrays and a few of their variants, as representatives of random access data structures. Then, lists are introduced, together with their sorted, linked, and circular versions. The book also explains limited access data structures, based on stacks and queues, including a priority and a circular queue. Following this, we introduce you to the dictionary data structure, which allows you to map keys to values and perform fast lookup. The sorted variant of a dictionary is supported, as well. If you want to benefit from high-performance, set-related operations, you can use another data structure, namely a hash set. One of the most powerful constructs is a tree, which exists in many variants, including a binary tree, a binary search tree, a self-balancing tree, a trie, and a heap. The last data structure we analyze is a graph, supported by many interesting algorithmic topics, such as graph traversal, minimum spanning tree, node coloring, and finding the shortest path.
Arrays, lists, stacks, queues, dictionaries, hash sets, trees, tries, heaps, and graphs, as well as accompanying algorithms – a broad range of subjects await you on the next pages! Let’s start the adventure and take the first step toward your mastery of data structures and algorithms, which hopefully will have a positive effect on your projects and on your career as a software developer!
Who this book is for
The book is aimed at developers who would like to learn about the data structures and algorithms that can be used with the C# language in various kind of applications, including web and mobile solutions. The topics presented here are suitable for programmers with various levels of experience, and even beginners will find interesting content. However, having at least basic knowledge of the C# programming language, such as about object-oriented programming, will be an added advantage.
It is worth noting that this book can contain some simplifications to make the subject easier to understand. What’s more, some data structures are only mentioned briefly, without detailed explanations or examples. The book’s aim is to interest you in the topic of data structures and algorithms, so you can further expand your knowledge with other books, research papers or on-line resources.
To easily understand the content, the book is equipped with many illustrations and examples. What is more, the source code for the accompanying projects is attached to the chapters and is available in the GitHub repository. Thus, you can easily run example applications and debug them without writing the code on your own.
It is worth mentioning that the code can be simplified and it can differ from the best practices. The examples can have significantly limited, or even no, security checks and functionalities. Before publishing your application using the content presented in the book, the application should be thoroughly tested to ensure that it works correctly in various circumstances, such as in the scenario of passing incorrect data.
What this book covers
Chapter 1
, Data Types, introduces you to the topic of the data types available while developing applications in the C# programming language, both value and reference ones. You will learn about the built-in value types, such as integral or floating-point numbers, as well as constants, enumerations, value tuples, user-defined struct types, and nullable value types. As for the reference types, you will see object and string types, classes, records, interfaces, and delegate and dynamic types, as well as nullable reference types.
Chapter 2
, Introduction to Algorithms, presents you with an algorithm definition and some real-world examples from your daily life. Then, you will learn a few notations for algorithms, namely natural language, a flowchart, pseudocode, and a programming language. Various types of algorithms are shown as well, including recursive, divide and conquer, back-tracking, greedy, heuristic, brute force, and dynamic programming. Computational complexity, including time complexity, is also presented and explained.
Chapter 3
, Arrays and Sorting, covers scenarios storing data using some representatives of random access data structures, namely arrays. First, three variants of arrays are explained, that is, single-dimensional, multi-dimensional, and jagged. You’ll also get to know seven popular sorting algorithms, namely selection sort, insertion sort, bubble sort, merge sort, Shell sort, quicksort, and heap sort. All of these algorithms are shown with illustrations, implementation code, and detailed explanations.
Chapter 4
, Variants of Lists, deals with other representatives of random access data structures, namely a few variants of lists. Lists are similar to arrays, but make it possible to dynamically increase the size of the collection if necessary. A few variants of lists, including a singly linked list, a doubly linked list, a circular singly linked list, and a circular doubly linked list are introduced. Such data structures are presented in illustrations, are implemented using C# code, and are explained in detail.
Chapter 5
, Stacks and Queues, explains how to use two variants of limited access data structures, namely stacks and queues, including priority and circular queues. The chapter shows how to perform push and pop operations on a stack, and also describes the enqueue and dequeue operations in the case of a queue. To aid your understanding of these topics, a few examples are presented, including the Tower of Hanoi game and an application that simulates a call center with multiple consultants and callers.
Chapter 6
, Dictionaries and Sets, focuses on data structures that make it possible to map keys to values, perform fast lookups, and carry out various operations on sets. The chapter introduces you to both non-generic and generic variants of a hash table, the sorted dictionary, and the high-performance solution to set operations allowing you to get union, intersection, subtraction, and symmetric difference. The sorted
set concept is shown, as well.
Chapter 7
, Variants of Trees, describes a few tree-related topics. First, it presents a basic tree, together with its implementation in C#, and examples showing it in action. The chapter also introduces you to binary trees, binary search trees, and self-balancing trees, namely AVL and red-black trees. Then, you’ll see a trie that is a great approach for performing string-related operations. The remainder of the chapter is dedicated to a brief introduction to the topic of binary heaps as other tree-based structures.
Chapter 8
, Exploring Graphs, contains a lot of information about graphs, starting with an explanation of their basic concepts, including nodes and a few variants of edges. The C#-based implementation of a graph is also covered. The chapter introduces you to two modes of graph traversal, namely depth-first and breadth-first search. Then, it presents the subject of minimum spanning trees using Kruskal’s and Prim’s algorithms, the node coloring problem, and finding the shortest path in a graph using Dijkstra’s algorithm.
Chapter 9
, See in Action, presents a few examples of various types of algorithms. You’ll see a recursive way to calculate a number from the Fibonacci series, with dynamic programming optimization. Then, you’ll learn a greedy approach to a minimum coin change problem, a divide-and-conquer method of getting the closest pair of points, a recursive way of generating fractals, a back-tracking and recursive way of solving rat in a maze and Sudoku puzzles, as well as a genetic algorithm and brute-force password guessing.
Chapter 10
, Conclusion, is the conclusion of all the knowledge acquired from the previous chapters. It shows a brief classification of data structures, dividing them into two groups, namely linear and nonlinear. Finally, the chapter talks about the diversity of applications of various data structures. Each data structure is presented with a brief description and some of them are also shown with illustrations, to help you remember the information learned while reading the previous nine chapters.
To get the most out of this book
The book is aimed at programmers with various experience. However, beginners will also find some interesting content. Nevertheless, at least a basic knowledge of C#, such as object-oriented programming, will be an added advantage.
You need to have the Visual Studio IDE installed, in the version supporting .NET 8.0. You can download Visual Studio 2022 Community for free from https://visualstudio.microsoft.com/free-developer-offers/
. The detailed step-by-step instructions on how to install it can be found at https://learn.microsoft.com/en-us/visualstudio/install/install-visual-studio?view=vs-2022
. Please keep in mind that the .NET desktop development option should be chosen in the Workloads tab while configuring the installation.
If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.
Download the example code files
You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/C-Sharp-Data-Structures-and-Algorithms---Second-Edition
If there’s an update to the code, it will be updated in the 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!
Conventions used
There are a number of text conventions used throughout this book.
Code in text: Indicates code words in text, folder names, filenames, file extensions, pathnames, and user input. Here is an example: The class contains three properties, namely Id, Name, and Role, as well as two constructors.
A block of code is set as follows:
int[,] numbers = new int[,]
{
{ 9, 5, -9 },
{ -11, 4, 0 },
{ 6, 115, 3 },
{ -12, -9, 71 },
{ 1, -6, -1 }
};
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
enum
CurrencyEnum { Pln, Usd, Eur };
Any command-line input or output is written as follows:
Name Birth date Temp. [C] -> Result
Marcin 09.11.1988 36.6 -> Normal
Adam 05.04.1995 39.1 -> High
Martyna 24.07.2003 35.9 -> Low
Bold: Indicates a new term, an important word, an important sentence, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: It sounds complicated, but fortunately, it is very simple. A jagged array could be understood as a single-dimensional array, where each element is another array.
Tips or important notes
Appear like this.
Get in touch
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, email us at [email protected]
and mention the book title in the subject of your message.
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
and fill in the form.
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.
Share Your Thoughts
Once you’ve read C# Data Structures and Algorithms, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page
for this book and share your feedback.
Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.
Download a free PDF copy of this book
Thanks for purchasing this book!
Do you like to read on the go but are unable to carry your print books everywhere?
Is your eBook purchase not compatible with the device of your choice?
Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.
Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.
The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily.
Follow these simple steps to get the benefits:
Scan the QR code or visit the link below
Download a free PDF copy of this bookhttps://packt.link/free-ebook/978-1-80324-827-1
Submit your proof of purchase
That’s it! We’ll send your free PDF and other benefits to your email directly
1
Data Types
Welcome to the first chapter in which you’ll start your amazing adventure with data structures and algorithms in the context of the C# programming language. First, we’ll provide a short introduction to this language. You will get to know how broad its possibilities are, in how many scenarios you can apply this language, as well as some basic constructions that you can use. This isn’t a C# course, so we won't be presenting various features one by one, and only a brief description will be provided.
The remaining part of this chapter is dedicated to data types, both built-in and user-defined, which you can use in your applications. First, you will learn what the difference is between value and reference types. Then, you will go through various available data types, starting with value types. Here, we will cover integral numeric types, floating-point numeric types, Boolean types, Unicode characters, constants, enumerations, value tuples, struct types, and nullable value types. Finally, we’ll cover reference types, including object and string types, as well as classes, records, interfaces, and delegates, together with dynamic and nullable reference types.
As you can see, you have quite a long journey before you. However, if you get to know the basics well, it will be much easier for you to get the most out of the content presented in the remainder of this book. I, as the author, am keeping my fingers crossed for you – good luck!
In this chapter, we will cover the following topics:
C# as a programming language
.NET-based console applications
The division of data types between value and reference types
Value types
Reference types
C# as a programming language
As a developer, you have probably heard about many programming languages, including C#, Java, C++, C, PHP, and Ruby. In all of them, you can use various data structures, as well as implement algorithms, to solve both basic and complex problems. However, each language has a specificity that’s visible while implementing data structures and accompanying algorithms. As mentioned previously, this book only focuses on the C# programming language. This is also the main topic of this section.
The C# language, pronounced C sharp, is a modern, general-purpose, strongly typed, and object-oriented programming language that can be used while developing a wide range of applications, such as web, mobile, desktop, distributed, and embedded solutions, as well as even games! It cooperates with various additional technologies and platforms, including ASP.NET Core, XAML, and Unity. Therefore, when you learn the C# language, as well as get to know more about data structures and algorithms in the context of this programming language, you can use such skills to create more than one particular type of software. What’s more, even if you decide to change your primary programming language to another, your knowledge regarding data structures and algorithms will still be useful. You might be wondering, how is this possible? The answer turns out to be very simple – you will understand how various data structures work, how you can implement them, as well as how you can apply them to solve various problems with specialized algorithms. But let’s go back to the C# language.
The current version of the language is C# 12. It is worth mentioning its interesting history in terms of various versions of the language (including 2.0, 3.0, 5.0, and 8.0) in which new features were added to increase language possibilities. When you take a look at the release notes for particular versions, you will see how the language is being improved and expanded over time to be a powerful and convenient solution for developers. New features are pretty awesome and can significantly simplify your work and allow you to refactor the code so that it’s shorter, as well as easier to understand and maintain. That’s great work that’s been done by the team developing C# that you can now benefit from while writing your code.
The syntax of the C# programming language is similar to other languages, such as Java or C++. For this reason, if you know such languages, you should easily be able to understand the code written in C#. As an example, similarly as in the languages mentioned previously, the code consists of statements that end with semicolons (;). The curly brackets, namely { and }, are used to group statements.
There are a few categories of statements, including the following:
Selection statements containing if and switch. The if statement allows you to conditionally execute code, depending on the provided condition. The switch statement makes it possible to choose a statement list to execute using the pattern match.
Iteration statements, including do-while, while, for, and foreach. They are related to loops and are used to execute a part of code many times while the condition is met.
Jump statements containing break, continue, and goto. They are used to control the execution of loops, such as to break it or move to the next iteration.
Exception-handling statements, including throw, try-catch, try-finally, and try-catch-finally. They are connected to handling exceptions that can be thrown in various parts of the code.
Other statements exist as well, such as lock, yield, checked, unchecked, and fixed. You will see some of the statements presented in the preceding list in the code snippets shown in the following chapters of this book, along with explanations.
Developing various applications in the C# language is also simplified by the availability of many additional great features, such as Language Integrated Query (LINQ), which allows developers to get data from various sources, including SQL databases and XML documents, consistently. There are also some approaches to shorten the required code, such as using Lambda expressions, pattern matching, properties, expression-bodied members, records, and string interpolations. It is worth mentioning automatic garbage collection, which greatly simplifies the task of releasing memory.
Where can you find more information?
You can learn more about the newest version of the C# language at https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-12
. The language history is shown at https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-version-history
. A set of detailed information about the language reference (including value and reference types) is available at https://learn.microsoft.com/en-us/dotnet/csharp/language-reference
. You can find there information about available data types with a set of details, including the supported value ranges and precisions, which are presented later in this chapter.
Of course, the solutions mentioned previously are only a very limited subset of features that are available while developing in C#. You will see some others in the following parts of this book, along with examples and detailed descriptions.
.NET-based console applications
To keep things simple, while reading this book, you will create many console-based applications, but the data structures and algorithms could be used in other kinds of solutions as well. The console-based applications will be created in Microsoft Visual Studio 2022 Community. This integrated development environment (IDE) is a comprehensive solution for developing various kinds of projects and is equipped with many great features that simplify the development and testing of your applications.
Just after launching the IDE, we can proceed by creating a new project. To create one, follow these steps:
Click on File | New | Project in the main menu.
Choose Console App on the right in the Create a new project window.
Type the name of the project (Project name), select a location for the files (Location), and enter the name of the solution (Solution name). Then, press Next.
In the Additional information window, set the framework version to .NET 8.0 (Long Term Support) and ensure that Do not use top-level statements is unchecked. If you are ready, click on the Create button to automatically create the project and generate the necessary files.
Congratulations! You’ve just created the first project. But what’s inside?
Let’s take a look at the Solution Explorer window, which presents the structure of the project. It is worth mentioning that the project is included in the solution with the same name. Of course, a solution could contain more than one project, which is a common scenario while developing more complex applications. You can see how it works if you browse the GitHub repository of this book. It contains one solution with over 40 projects.
Don’t have Solution Explorer?
If you cannot find the Solution Explorer window, you can open it by choosing the View | Solution Explorer option from the main menu. Similarly, you could open other windows, such as Output or Class View. If you cannot find a suitable window (for example, C# Interactive) directly within the View option, you can find it in the View | Other Windows node.
The automatically generated project contains the Dependencies element, which presents additional dependencies used by the project. It is worth noting that you could easily add references by choosing the Add Project Reference, Add Shared Project Reference, or Add COM Reference option from the context menu of the Dependencies element. Moreover, you can install additional packages using NuGet Package Manager, which can be launched by choosing Manage NuGet Packages from the Dependencies context menu.
Write from scratch or reuse existing packages?
It is a good idea to take a look at packages that are already available before writing the complex module on your own since a suitable package could already be available for developers. In such a case, you could