<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Gavin Lon - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Gavin Lon - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Mon, 18 May 2026 22:34:29 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/GavinLon/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ Learn the C# Programming Language – Full Book for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ C# version 1 was released in January 2002. It is a modern, general purpose programming language designed and developed from the ground up by the renowned Danish software engineer, Anders Heijleberg and his team at Microsoft. I’ve heard Anders Heijlsb... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-csharp-book/</link>
                <guid isPermaLink="false">66b0c58dece58de64f5e1dc9</guid>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                    <category>
                        <![CDATA[ book ]]>
                    </category>
                
                    <category>
                        <![CDATA[ C# ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Gavin Lon ]]>
                </dc:creator>
                <pubDate>Tue, 06 Feb 2024 22:35:57 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/02/The-C--Handbook---Version-4-Cover.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>C# version 1 was released in January 2002. It is a modern, general purpose programming language designed and developed from the ground up by the renowned Danish software engineer, Anders Heijleberg and his team at Microsoft.</p>
<p>I’ve heard Anders Heijlsberg say in an interview that with C# the goal was to provide the power and expressiveness of C++ and the RAD (Rapid Application Development) capabilities of Visual Basic.</p>
<p>C# is similar to Java in the sense that it runs within its own environment. Java runs within an environment known as the JRE (Java Runtime Environment) whereas C# runs in an environment known as .NET. Both the JRE and .NET run on top of the relevant operating system.</p>
<p>The first version of .NET is known as the .NET Framework which needs to be deployed to the target computer in its entirely and can only run on Windows platforms. But now, .NET has evolved into an environment that can run on multiple platforms like Windows, Mac OS, Linux, IOS, Android and more.</p>
<p>The .NET environment became fragmented in 2016 with the release of .NET Core, which enabled .NET to be cross platform and agile in the sense that only your application’s base class library dependencies need to be deployed to the target computer with your application.</p>
<p>Then in 2020, .NET became unified with the release of NET 5, which meant that the confusion created by having two strands of .NET, namely .NET Framework and .NET Core, was alleviated.</p>
<p>The latest stable release of C# is a highly evolved, sophisticated programming language that allows you to create almost any kind of application that can run on multiple platforms. You can create a single code base that can run on multiple platforms, for example Linux, Mac OS, Android, IOS, in the Cloud, of course Windows operating systems and more.</p>
<p>You are able to write and build your C# applications using free tools like Visual Studio 2022 Community edition or the cross platform, light weight tool, Visual Studio Code. Visual Studio Code can run on Windows, Mac OS, and Linux platforms.</p>
<p>C# is a highly versatile programming language. You can build many types of applications, such as web-based applications using ASP .NET, cross platform mobile and desktop applications using the .Net MAUI framework, Internet of things applications, AI applications using ML.NET, cloud native applications, games and more.</p>
<p>C# has a huge support base, backed by Microsoft, and is constantly evolving. A new version of .NET is shipped every November, which always contains many improvements and enhancements. This means that .NET is forever evolving, improving, and keeping up with the latest trends in technology.</p>
<p>C# is a well designed, modern, general purpose programming language that will be a great addition to your developer toolkit. So let's dive in.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-introduction-to-net">Introduction to .NET</a></li>
<li><a class="post-section-overview" href="#heading-free-tools-available-for-creating-c-applications">Free Tools Available for Creating C# Applications</a><ul>
<li><a class="post-section-overview" href="#heading-create-a-basic-console-app-using-visual-studio-community-edition">Create a Basic Console App using Visual Studio Community Edition</a><ul>
<li><a class="post-section-overview" href="#heading-the-main-method-application-entry-point">The Main Method (Application Entry Point)</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-how-to-create-a-basic-console-app-using-visual-studio-code">Creating a Basic Console App using Visual Studio Code</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-c-data-types">C# Data Types</a><ul>
<li><a class="post-section-overview" href="#heading-value-types-and-reference-types">Value Types and Reference Types</a></li>
<li><a class="post-section-overview" href="#heading-c-built-in-value-types">C# Built-in Value Types</a></li>
<li><a class="post-section-overview" href="#heading-c-built-in-reference-types">C# Built-in Reference Types</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-c-strings">C# Strings</a><ul>
<li><a class="post-section-overview" href="#heading-immutability-of-c-strings">Immutability of C# Strings</a></li>
<li><a class="post-section-overview" href="#heading-quoted-string-literals-verbatim-string-literals-and-raw-string-literals">Quoted String Literals, Verbatim String Literals and Raw String Literals</a><ul>
<li><a class="post-section-overview" href="#heading-quoted-string-literals">Quoted String Literals</a></li>
<li><a class="post-section-overview" href="#heading-verbatum-string-literals">Verbatum String Literals</a></li>
<li><a class="post-section-overview" href="#heading-raw-string-literals">Raw String Literals</a></li>
</ul>
</li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-useful-c-built-in-string-methods">Useful C# Built-in String Methods</a><ul>
<li><a class="post-section-overview" href="#heading-the-indexof-built-in-method">The IndexOf Built-in Method</a></li>
<li><a class="post-section-overview" href="#heading-the-replace-built-in-method">The Replace Built-in Method</a></li>
<li><a class="post-section-overview" href="#heading-the-substring-built-in-method">The Substring Built-in Method</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-c-data-type-conversion">C# Data Type Conversion</a><ul>
<li><a class="post-section-overview" href="#heading-implicit-vs-explicit-data-type-conversion">Implicit vs Explicit Data Type Conversion</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-c-operators">C# Operators</a><ul>
<li><a class="post-section-overview" href="#heading-types-of-c-operators">Types of C# Operators</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-constants-and-read-only-variables">Constants and Read-only Variables</a><ul>
<li><a class="post-section-overview" href="#heading-introduction-to-constants">Introduction to Constants</a></li>
<li><a class="post-section-overview" href="#heading-introduction-to-read-only-variables">Introduction to Read-only Variables</a></li>
<li><a class="post-section-overview" href="#heading-code-example-using-a-const">Code Example Using a Const</a></li>
<li><a class="post-section-overview" href="#heading-code-example-using-a-read-only-variable">Code Example Using a Read-only Variable</a></li>
<li><a class="post-section-overview" href="#heading-code-example-of-the-incorrect-use-of-a-read-only-variable">Code Example of the Incorrect Use of a Read-only Variable</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-c-if-else-if-else-statements">C# if / else if / else Statements</a><ul>
<li><a class="post-section-overview" href="#heading-basic-ifelse-conditional-logic">Basic if/else Conditional Logic</a></li>
<li><a class="post-section-overview" href="#heading-implementing-ifelse-ifelse-conditional-logic">Implementing if/else if/else Conditional Logic</a></li>
<li><a class="post-section-overview" href="#heading-nested-if-statements">Nested if Statements</a></li>
<li><a class="post-section-overview" href="#heading-more-complex-conditional-expressions">More Complex Conditional Expressions</a><ul>
<li><a class="post-section-overview" href="#heading-the-ampamp-operator">The &amp;&amp; Operator</a></li>
<li><a class="post-section-overview" href="#heading-the-operator">The || Operator</a></li>
</ul>
</li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-c-loops">C# Loops</a><ul>
<li><a class="post-section-overview" href="#heading-the-for-loop">The for Loop</a></li>
<li><a class="post-section-overview" href="#heading-the-while-loop">The while Loop</a></li>
<li><a class="post-section-overview" href="#heading-the-do-while-loop">The do-while Loop</a></li>
<li><a class="post-section-overview" href="#heading-the-foreach-loop">The foreach Loop</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-c-arrays">C# Arrays</a><ul>
<li><a class="post-section-overview" href="#heading-one-dimensional-arrays">One-dimensional Arrays</a></li>
<li><a class="post-section-overview" href="#heading-multi-dimensional-arrays">Multi-dimensional Arrays</a><ul>
<li><a class="post-section-overview" href="#heading-two-dimensional-arrays">Two-dimensional Arrays</a></li>
<li><a class="post-section-overview" href="#heading-three-dimensional-arrays">Three-dimensional Arrays</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-jagged-arrays">Jagged Arrays</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-c-methods">C# Methods</a><ul>
<li><a class="post-section-overview" href="#heading-introduction-to-methods-in-c">Introduction to Methods</a></li>
<li><a class="post-section-overview" href="#heading-the-main-method">The Main Method</a></li>
<li><a class="post-section-overview" href="#heading-the-structure-of-methods">The Structure of Methods</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-c-classes">C# Classes</a><ul>
<li><a class="post-section-overview" href="#heading-the-class-keyword">The 'class' Keyword</a></li>
<li><a class="post-section-overview" href="#heading-the-public-access-modifier">Public Access Modifier</a></li>
<li><a class="post-section-overview" href="#heading-the-private-member-variable">Private Member Variable</a></li>
<li><a class="post-section-overview" href="#heading-the-constructor">The Constructor</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-c-structs">C# Structs</a><ul>
<li><a class="post-section-overview" href="#heading-key-differences-between-a-class-and-a-struct">Key Differences Between a Class and a Struct</a></li>
<li><a class="post-section-overview" href="#heading-use-a-struct-in-code">Use a Struct in Code</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-enums-and-switch-statements">Enums and Switch Statements</a><ul>
<li><a class="post-section-overview" href="#heading-introduction-to-enums">Introduction to Enums</a></li>
<li><a class="post-section-overview" href="#heading-use-an-enum-in-code">Use an Enum in Code</a></li>
<li><a class="post-section-overview" href="#heading-using-a-switch-statement-in-code-with-an-enum">Using a switch Statement in Code with an enum</a></li>
<li><a class="post-section-overview" href="#heading-associating-one-code-block-with-more-than-one-case">Associating One Code Block with More than One Case</a></li>
<li><a class="post-section-overview" href="#heading-using-strings-in-switch-statements">Using Strings in switch Statements</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-inheritance-in-c">Inheritance in C#</a></li>
<li><a class="post-section-overview" href="#heading-abstraction-in-c">Abstraction in C#</a></li>
<li><a class="post-section-overview" href="#heading-c-exception-handling">C# Exceptions</a></li>
<li><a class="post-section-overview" href="#heading-c-delegates">C# Delegates</a></li>
<li><a class="post-section-overview" href="#heading-c-events">C# Events</a></li>
<li><a class="post-section-overview" href="#heading-c-generics">C# Generics</a></li>
<li><a class="post-section-overview" href="#heading-linq">LINQ</a></li>
<li><a class="post-section-overview" href="#heading-c-attributes">C# Attributes</a></li>
<li><a class="post-section-overview" href="#heading-reflection-in-c">Reflection</a></li>
<li><a class="post-section-overview" href="#heading-video-on-asynchronous-programming-in-c">Video on Asynchronous Programming in C#</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-introduction-to-net">Introduction to .NET</h2>
<p>As we briefly discussed in the introductory section, .NET provides an environment in which your C# applications run.</p>
<p>An essential feature of .NET is what can be described as a virtual machine known as the CoreCLR or Core Common Language Runtime.</p>
<p>The Core Common Language Runtime provides services like Just-in-time compilation, memory management, garbage collection, security and exception handling. Also provided with .NET is a variety of base class libraries, that provide generic functionality that can be leveraged by your C# code.</p>
<p>The first version of .NET was the .NET Framework which was released in 2002. .NET Framework could only run on certain windows platforms and had to be installed in its entirety on the target computer.</p>
<p>.NET Core was released in 2016 and provided a modular, cross platform version of .NET that is optimized for the cloud. A significant feature of .NET Core was that only the dependencies used by your application needed to be shipped to the target computer, unlike .NET Framework that had to exist in its entirety on the target computer.</p>
<p>The rapid evolution of these two versions of .NET, .NET Framework and .NET Core, resulted in growing fragmentations of .NET.</p>
<p>In order to deal with the continuing fragmentation of .NET, Microsoft created the .NET Standard, where all platforms running .NET had to support .NET Standard. This was the first step in unifying .NET but it was a temporary solution.</p>
<p>Then in November 2020, .NET 5 was released. This version of .NET retained the great features of both .NET Framework and .NET core, but this release was significant in that .NET 5 meant that .NET was now unified under one umbrella (as it were). There is now no more .NET Framework and .NET core – rather just one version of .NET moving forward.</p>
<p>With the release of .NET 6 the following year, in November 2021, came many significant improvements and new features. Perhaps what is most significant about .NET 6, is that it cemented the unification of .NET.</p>
<p>At this point in time, .NET is a cross platform, modular, agile, fast, robust and secure environment in which your C# applications can run. This means C# and .NET have now evolved to a point where you can “write once and run anywhere”.</p>
<p>Here's a video overview about how .NET works in more detail:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/P6lJA3E3Uog" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>And for a full video series on the evolution of .NET, you can check this out:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/OkeM7XVwEdA" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-free-tools-available-for-creating-c-applications">Free Tools Available for Creating C# Applications</h2>
<p>Microsoft provides two sophisticated free tools that you can use for creating C# applications: Visual Studio Community Edition, which is an IDE (Integrated Development Environment) that can run on Windows platforms, and Visual Studio Code (a light weight code editor) that can run on Windows, Mac OS, and Linux platforms.</p>
<p>You can download and install Visual Studio Community Edition 2022 and the latest version of Visual Studio Code from here: <a target="_blank" href="https://visualstudio.microsoft.com/downloads/">https://visualstudio.microsoft.com/downloads/</a>.</p>
<h3 id="heading-create-a-basic-console-app-using-visual-studio-community-edition">Create a Basic Console App using Visual Studio Community Edition</h3>
<p>The easiest way to create your first C# application is by using the simplest project template made available to you through Visual Studio.</p>
<p>The simplest project template is named “Console App”. To get started building your first C# application using Visual Studio, just follow the instructions below:</p>
<ul>
<li>Launch Visual Studio</li>
<li>From the “Get Started” section on the dialog presented to you, select “Create a new project”.</li>
<li>Find the project template named, “Console App”.</li>
<li>Select the “Console App” project template option and press the “Next” button.</li>
<li>Provide a name for your project and the location on your hard disk drive where you’d like to store the files for your project. Press the “Next” button.</li>
<li>At the time of the creation of this book, the latest stable release of .NET is .NET version 8. If you have this latest version installed on your target computer, it will be selected in the relevant dropdown list for the field marked “Framework”.</li>
<li>Press the ‘Create’ button to generate the files for your C# project.</li>
</ul>
<p>You can check out the YouTube video below for a demonstration of creating a basic "Console App" project using Visual Studio 2022.</p>
<p>In this YouTube video, the first demonstration of creating a basic project shows how to create a "Console App" project that includes top-level statements (that is, the <code>Main</code> method definition is not present by default).</p>
<p>The second demonstration shows the creation of a basic "Console App" project that doesn't include top-level statements. You'll see how the <code>Main</code> method is shown in the default code, whereas in the first demonstration only the body of the <code>Main</code> method is shown, and the actual <code>Main</code> method definition is not present.</p>
<p>Note that the <code>Main</code> method is always the entry point of C# applications. Where top-level-statements are included, the <code>Main</code> method is still there but is not visible by default in your code. The inclusion of top-level-statements results in a reduced amount of boilerplate code needed in order for a developer to get started.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/10QrZCLfuCQ" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h4 id="heading-the-main-method-application-entry-point">The Main Method (Application Entry Point)</h4>
<p>If you look at the "Program.cs" file, you’ll see the following code:</p>
<pre><code class="lang-csharp">
    Console.WriteLine(“Hello World”);
</code></pre>
<p>You can run this code by pressing the play button on your toolbar. The code for this application is very basic and simply outputs the line, "Hello World" to the console screen.</p>
<p>If you look at the code in the "Program.cs" file, it may seem that there is no real entry point to the application. This is specificially when you have elected to use top-level-statements. If you have written code in previous versions of .NET, the absence of a <code>Main</code> method will be conspicuous.</p>
<p>So in .NET 5, for example, the same code currently in your application would look different because the program class and within it the <code>Main</code> method would be included.</p>
<p>Check out the code depicted in figure 1 for an example of this:</p>
<p>Figure 1.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">namespace</span> <span class="hljs-title">CSharpSampleCode</span>
{
    <span class="hljs-keyword">internal</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Program</span>
    {
        <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"><span class="hljs-keyword">string</span>[] args</span>)</span>
        {
            Console.WriteLine(<span class="hljs-string">"Hello, World!"</span>);
        }
    }
}
</code></pre>
<p>In .NET 6, a marked effort was made to simplify the amount of boilerplate code needed in your applications. Note that with C# 10, you can simply write the body of the <code>Main</code> method in the "Program.cs" file. You don't need to include a class definition (and within the relevant class, a <code>Main</code> method definition) as is depicted in figure 1.</p>
<p>So the relevant statements do not need to reside within a <code>Main</code> method. The statements can exist as what’s known as top-level-statements.</p>
<p>A <code>Main</code> method does still exist behind the scenes and is still the entry point for all C# applications. But after the release of .NET 6, the <code>Main</code> method does not need to be present within your code because the compiler synthesises a <code>Program</code> class with a <code>Main</code> method and places all your top-level-statements within the <code>Main</code> method.</p>
<p>But this is now done behind the scenes. The term top-level-statements means that you're able to write statements that are not wrapped in a <code>Main</code> method within a class. Behind the scenes the <code>Main</code> method and relevant class are created by the compiler. So you're able to write a lot less code, and the entry point of the application – that used to be explicitly written using the <code>Main</code> method – is now synthesised by the C# compiler.</p>
<p>Figure 2 depicts how you can avoid writing multiple lines of code for the <code>Main</code> method (the entry point for a C# application).</p>
<p>Figure 2.</p>
<pre><code class="lang-csharp">Console.WriteLine(<span class="hljs-string">"Hello, World!"</span>); <span class="hljs-comment">//The ‘Main' method is not visible within the code</span>
</code></pre>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/2pquQMSYk6c" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h3 id="heading-how-to-create-a-basic-console-app-using-visual-studio-code">How to Create a Basic Console App using Visual Studio Code</h3>
<p>I'll now walk you through the process of creating a console application using Visual Studio Code.</p>
<p>First, you'll need to launch VS Code. For the best experience coding an application in C#, you should install the C# Dev Kit extension using the Extensions view.</p>
<p>You can bring up the Extensions view by clicking the Activity Bar on the side of Visual Studio Code. You can then search for C# Dev Kit and install this extension.</p>
<p>Next, create a local folder where you’d like to store the files for your C# project anywhere on your computer.</p>
<p>Using the File &gt; Open Folder menu option, open the folder you created in the previous step, from within VS Code.</p>
<p>Then launch the terminal window using the View &gt; Terminal menu option. You can also launch the terminal window by pressing ctrl + `</p>
<p>You’ll need to ensure that you have installed an appropriate version of the .NET SDK. The latest stable release is .NET version 8. You can download the recommended install file from this location, <a target="_blank" href="https://dotnet.microsoft.com/download">https://dotnet.microsoft.com/download</a>.</p>
<p>In order to verify that you have installed the .NET SDK, you can type <code>dotnet —-version</code> within the terminal window and then press the enter key.</p>
<p>To create a project based on the "Console App" project template, you can type this command at your command prompt: <code>dotnet new console</code>. Then press the enter key.</p>
<p>To run the project, type <code>dotnet run</code> at the command prompt and press the enter key.</p>
<p>After you have appropriately updated the code in your 'Program.cs' file, remember to save your changes before running the updated code.</p>
<p>As an exercise, change the the code so that the output is 'Hello C#', then save your code, and then run your code by typing in, <code>dotnet run</code> in the terminal window. Once you press the enter key, 'Hello C#' should be outputted to your console screen.</p>
<p>For a detailed video guide on how to use Visual Studio Code to create C# applications, you can watch the following YouTube video:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/rab_1cFQUF4" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-c-data-types">C# Data Types</h2>
<p>It's important to note that C# is a statically typed programming language, whereas JavaScript and Python, for example, are both dynamically typed.</p>
<p>This means that in C#, when variables are declared at compile time, the variables must be defined as a specific C# type.</p>
<p>An exception to this rule is made through the use of the <code>dynamic</code> type. The <code>dynamic</code> data type allows you to circumvent the .Net type system. If a variable is declared as the <code>dynamic</code> data type, this is similar to how variables are typed in a dynamically typed language like JavaScript.</p>
<p>In most cases, you should strongly type variables so that you can reap the benefits inherent in a statically typed language. The advantage of strongly typing variables is that potential data type-related errors can be flagged at compiled time and then dealt with appropriately at compile time.</p>
<p>If you create code that is not valid in relation to the type used to define a variable, this can be flagged by the C# compiler at compile time.</p>
<p>If you look at the code example in figure 3, the C# code is invalid because variable <code>a</code> is defined as an integer and in the <code>DoSomething</code> method, the <code>a</code> variable is assigned a string value.</p>
<p>The C# compiler flags the exception at compile time, and the exception is represented within the Visual Studio IDE, where a red squiggly line is drawn under the offending code.</p>
<p>Figure 3.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">internal</span> <span class="hljs-keyword">class</span> <span class="hljs-title">SomeClass</span>
{
    <span class="hljs-keyword">int</span> a = <span class="hljs-number">1</span>;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">DoSomething</span>(<span class="hljs-params"></span>)</span>
    {
        a = <span class="hljs-string">"Gavin Lon"</span>; <span class="hljs-comment">// Compile time error stating: "Cannot implicitly convert type 'string' to 'int'"</span>
    }
}
</code></pre>
<p>So the code fails to compile and the cause of the compile time exception is made clear to you through a red squiggly line which appears under the offending code.</p>
<p>This safeguards type-related exceptions from being deployed to a production environment where code that is not appropriately checked at compile time could be prone to runtime errors.</p>
<p>Statically typed languages ensure better code robustness at runtime than dynamically typed languages. C# also performs better than dynamically typed languages like JavaScript or Python because the use of statically typed variables means that the type of the variable is known at compile time. This means that variable types do not need to be determined at runtime, which is what happens with dynamically typed languages.</p>
<p>With dynamically typed languages, the type of a variable is determined at runtime based on the value assigned to the relevant variable. With statically typed languages like C#, the type is known, as it were, at compile time – so the added step of determining the variable's type at runtime is not necessary. This results a performance advantage over dynamically typed code.</p>
<h3 id="heading-value-types-and-reference-types">Value Types and Reference Types</h3>
<p>C# data types can be put into two main classifications: value types and reference types. These main data type classifications denote how data for C# data types are stored in memory.</p>
<p>A value type is stored in a memory location called the stack, where the value assigned to a variable is stored in the relevant memory space on the stack.</p>
<p>A reference type is stored in a memory location known as the heap, where an address of where the actual data is stored resides on the stack and points to the location where the actual data is stored on the heap.</p>
<p>A key difference between data stored on the stack and data stored on the heap is that all data stored on the stack has a fixed size, where data stored on the heap does not have a fixed size. the fixed size for discrete data stored on the stack means more efficiency in the storage and retrieval of such data when compared to the management of data stored on the heap.</p>
<p>A very basic example that highlights the significance of value types and references types is the following:</p>
<p>Let’s say an integer named <code>a</code> is assigned a value of <code>1</code>, and an integer named <code>b</code> is assigned the value stored in <code>a</code>. Then let’s say that the value of <code>3</code> is assigned to variable <code>a</code>. Does this assignment affect the value stored in variable <code>b</code>?</p>
<p>The answer is no. This is because the integer data type is a value type. The <code>a</code> variable’s data and the <code>b</code> variable’s data are stored in completely different memory locations on the stack. So a change to the data stored in variable <code>a</code> will not affect the data stored in variable <code>b</code>, even though the value stored in <code>a</code> was assigned to the <code>b</code> variable.</p>
<p>Figure 4.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">int</span> a = <span class="hljs-number">1</span>;
<span class="hljs-keyword">int</span> b = a;
a = <span class="hljs-number">3</span>;
</code></pre>
<p>The object data type in C# is the root type for all data types in C#. An object data type is a reference type, and so all types that inherit directly from the object data type are reference types.</p>
<p>In the example below (in figure 5), variable <code>a</code>, which is defined as the <code>Employee</code> user defined type, is assigned a new <code>Employee</code> object, where the <code>Name</code> property is set to the string value of <code>"Gavin Lon"</code>. Variable <code>b</code>, which is defined as the <code>Employee</code> user defined type, is assigned the value of <code>a</code>.</p>
<p>When the <code>Name</code> property of object variable <code>a</code> is changed to <code>David Hasslehoff</code>, the <code>Name</code> property of object variable <code>b</code> is automatically changed to <code>"David Hasslehof"</code>.</p>
<p>This is because when <code>b</code> is assigned the value stored in <code>a</code>, the data stored in <code>a</code> is not copied to the storage location that stores the data in <code>b</code>. A memory address is copied to <code>b</code>, which contains the memory location of where the data is stored for variable <code>a</code>. The actual data is stored on the heap and only the memory location of where the data is stored on the heap, is stored on the stack.</p>
<p>This means that variable <code>a</code> and variable <code>b</code> reference the same data (stored on the heap) at this point. So when the <code>Name</code> property of object variable <code>a</code> is changed to <code>"David Hasslehof"</code>, this change also affects variable <code>b</code>. So the <code>Name</code> property in variable <code>b</code> will also reflect <code>"David Hasselhof"</code>.</p>
<p>Figure 5.</p>
<pre><code class="lang-csharp">Employee a = <span class="hljs-keyword">new</span> Employee { Id = <span class="hljs-number">1</span>, Name = <span class="hljs-string">"Gavin Lon"</span> };
Employee b = a;
a.Name = <span class="hljs-string">"David Hasslehof"</span>;
Console.WriteLine(b.Name); <span class="hljs-comment">// This code prints out the value of David Hasslehof</span>
</code></pre>
<h3 id="heading-c-built-in-value-types">C# Built-in Value Types</h3>
<p>You can see below, in figure 6, the built-in value type data types in C#. Each item contains a link to an appropriate Microsoft Learn page so that you can read more about the relevant data type.</p>
<p>Figure 6.</p>
<table><thead><tr><th>C# type keyword</th><th>.NET type</th></tr></thead><tbody><tr><td><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/bool"><code>bool</code></a></td><td><a href="https://learn.microsoft.com/en-us/dotnet/api/system.boolean" class="no-loc">System.Boolean</a></td></tr><tr><td><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/integral-numeric-types"><code>byte</code></a></td><td><a href="https://learn.microsoft.com/en-us/dotnet/api/system.byte" class="no-loc">System.Byte</a></td></tr><tr><td><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/integral-numeric-types"><code>sbyte</code></a></td><td><a href="https://learn.microsoft.com/en-us/dotnet/api/system.sbyte" class="no-loc">System.SByte</a></td></tr><tr><td><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/char"><code>char</code></a></td><td><a href="https://learn.microsoft.com/en-us/dotnet/api/system.char" class="no-loc">System.Char</a></td></tr><tr><td><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/floating-point-numeric-types"><code>decimal</code></a></td><td><a href="https://learn.microsoft.com/en-us/dotnet/api/system.decimal" class="no-loc">System.Decimal</a></td></tr><tr><td><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/floating-point-numeric-types"><code>double</code></a></td><td><a href="https://learn.microsoft.com/en-us/dotnet/api/system.double" class="no-loc">System.Double</a></td></tr><tr><td><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/floating-point-numeric-types"><code>float</code></a></td><td><a href="https://learn.microsoft.com/en-us/dotnet/api/system.single" class="no-loc">System.Single</a></td></tr><tr><td><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/integral-numeric-types"><code>int</code></a></td><td><a href="https://learn.microsoft.com/en-us/dotnet/api/system.int32" class="no-loc">System.Int32</a></td></tr><tr><td><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/integral-numeric-types"><code>uint</code></a></td><td><a href="https://learn.microsoft.com/en-us/dotnet/api/system.uint32" class="no-loc">System.UInt32</a></td></tr><tr><td><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/integral-numeric-types"><code>nint</code></a></td><td><a href="https://learn.microsoft.com/en-us/dotnet/api/system.intptr" class="no-loc">System.IntPtr</a></td></tr><tr><td><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/integral-numeric-types"><code>nuint</code></a></td><td><a href="https://learn.microsoft.com/en-us/dotnet/api/system.uintptr" class="no-loc">System.UIntPtr</a></td></tr><tr><td><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/integral-numeric-types"><code>long</code></a></td><td><a href="https://learn.microsoft.com/en-us/dotnet/api/system.int64" class="no-loc">System.Int64</a></td></tr><tr><td><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/integral-numeric-types"><code>ulong</code></a></td><td><a href="https://learn.microsoft.com/en-us/dotnet/api/system.uint64" class="no-loc">System.UInt64</a></td></tr><tr><td><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/integral-numeric-types"><code>short</code></a></td><td><a href="https://learn.microsoft.com/en-us/dotnet/api/system.int16" class="no-loc">System.Int16</a></td></tr><tr><td><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/integral-numeric-types"><code>ushort</code></a></td><td><a href="https://learn.microsoft.com/en-us/dotnet/api/system.uint16" class="no-loc">System.UInt16</a></td></tr></tbody></table>

<h3 id="heading-c-built-in-reference-types">C# Built-in Reference Types</h3>
<p>And you can also see all of the built-in reference type data types in C# in figure 7.</p>
<p>Figure 7.</p>
<table><thead><tr><th>C# type keyword</th><th>.NET type</th></tr></thead><tbody><tr><td><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/reference-types#the-object-type"><code>object</code></a></td><td><a href="https://learn.microsoft.com/en-us/dotnet/api/system.object" class="no-loc">System.Object</a></td></tr><tr><td><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/reference-types#the-string-type"><code>string</code></a></td><td><a href="https://learn.microsoft.com/en-us/dotnet/api/system.string" class="no-loc">System.String</a></td></tr><tr><td><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/reference-types#the-dynamic-type"><code>dynamic</code></a></td><td><a href="https://learn.microsoft.com/en-us/dotnet/api/system.object" class="no-loc">System.Object</a></td></tr></tbody></table>

<p>And now you can check out two YouTube videos where C# data types and C# variables are discussed. Code examples are also provided.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/sW-fsSJaFA0" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/rM9HostBLJ4" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-c-strings">C# Strings</h2>
<p>In C#, you can define a string using the <code>System.String</code> class or using its alias, <code>string</code>. In the example depicted in figure 8, the two lines of code are equivalent:</p>
<p>Figure 8.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">string</span> fullName = <span class="hljs-string">"Gavin Lon"</span>;
System.String fullName = <span class="hljs-string">"Gavin Lon"</span>;
</code></pre>
<p>A string is simply a reference to an object in memory that stores text. Internally, a string is an array of char objects.</p>
<p>To create a new string object, the <code>new</code> keyword is not generally used. The <code>new</code> keyword is only used to create a new string when an array of char objects is passed as an argument to the constructor of the relevant string object.</p>
<p>You can see an example of this below in figure 9.</p>
<p>Figure 9.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">char</span>[] nameCharacters = { <span class="hljs-string">'G'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'v'</span>, <span class="hljs-string">'i'</span>, <span class="hljs-string">'n'</span>, <span class="hljs-string">' '</span>, <span class="hljs-string">'L'</span>, <span class="hljs-string">'o'</span>, <span class="hljs-string">'n'</span> };
<span class="hljs-keyword">string</span> fullName = <span class="hljs-keyword">new</span> <span class="hljs-keyword">string</span>(nameCharacters);
</code></pre>
<h3 id="heading-immutability-of-c-strings">Immutability of C# Strings</h3>
<p>Strings are reference types, which means a numeric reference to a memory address is stored on the stack and points to the actual string data which is stored on the heap.</p>
<p>The difference between the string reference type and other reference types (like, for example, an object instantiated from a class) is that the data for a particular string (stored on the heap) cannot be directly changed in memory. This means that every time, for example, a concatenation operation occurs in code, the memory address stored on the stack is simply amended to point to a new memory location on the heap that stores the new string that has been created as a result of the relevant concatenation operation.</p>
<h3 id="heading-quoted-string-literals-verbatim-string-literals-and-raw-string-literals">Quoted String Literals, Verbatim String Literals and Raw String Literals</h3>
<h4 id="heading-quoted-string-literals">Quoted String Literals</h4>
<p>Quoted string literals are string values defined on one line in code that start with a single double quote character and end with a single double quote character. Quoted string literals are best suited for stings that exist on one line and don’t contain escape sequences.</p>
<p>If you were to include a backslash (<code>\</code>) character in a quoted string literal (like when expressing a directory path, for example), you would need to escape the backslash character with a backslash character directly preceding the backslash character you wish to output as part of the string.</p>
<p>Here's an example of this depicted in figure 11.</p>
<p>Figure 11.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">string</span> path = <span class="hljs-string">"C:\\development\\CSharpProjects"</span>;
Console.Write(path);
<span class="hljs-comment">// Output: C:\development\CSharpProjects</span>
</code></pre>
<p>The <code>\</code> character has a special meaning in C#, so it must be escaped with the appropriate escape character – which is the <code>\</code> character. To make it clear that the <code>\</code> character is an escape character used in C# string literals, see the below example (in figure 12) where the <code>\</code> character is used to escape the double quote (<code>"</code>) characters included in a string literal.</p>
<p>Figure 12.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">string</span> path = <span class="hljs-string">"\"C:\\development\\CSharpProjects\""</span>;
Console.WriteLine(path);
<span class="hljs-comment">//Output: "C:\development\CSharpProjects"</span>
</code></pre>
<h4 id="heading-verbatum-string-literals">Verbatum String Literals</h4>
<p>Verbatim string literals are recommended where quotations and backslash characters need to be included in the output for string literals. If you precede a string literal with the <code>@</code> symbol, the relevant code can output the relevant string verbatim.</p>
<p>Note how the code in figure 13 outputs the same result as the code depicted in figure 12.</p>
<p>Figure 13.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">string</span> path = <span class="hljs-string">@"""C:\development\CSharpProjects"""</span>;
Console.WriteLine(path);
<span class="hljs-comment">// Output: "C:\development\CSharpProjects"</span>
</code></pre>
<p>The output is the same when the same string lateral is represented in code as a quoted string literal and as a verbatim string literal.</p>
<p>But using a verbatim string literal is much easier to read and is cleaner in its representation. So where the backslash and double quote symbols need to be outputted within the string literal, it's better to use a verbatim string literal.</p>
<p>It's also better to use a verbatim string literal for code that outputs multiline text. In figure 14 is a code example where a verbatim string literal is used in code to output multiline text.</p>
<p>Figure 14.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">string</span> narrative =
    <span class="hljs-string">@"Humpty Dumpty sat on the wall
Humpty Dumpty had a great fall
all the kings horses and all the kings men
couldn’t put Humpty together again"</span>;
</code></pre>
<p>So the above code example dipicted in figure 14 would output the narrative as it is written in the literal string – that is, the text is outputted on multiple lines as the text appears within the literal string in code.</p>
<h4 id="heading-raw-string-literals">Raw String Literals</h4>
<p>C# 11 introduced raw string literals. These make it even easier to write code to output multiline text.</p>
<p>Raw string literals remove the need to ever use escape sequences within literal strings.</p>
<p>To indicate in code that you are using a raw string literal, you wrap the relevant text in three double quote symbols. So the first 3 characters should be three double quote symbols followed by the literal string, and the last 3 characters must be three double quote symbols.</p>
<p>Note that in this example, the three quotes that wrap the string literal appear on their own line. This is important because in this example the first part of the string literal appears within double quotes.</p>
<p>Note the output of the code below in figure 15.</p>
<p>Figure 15.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">string</span> text = <span class="hljs-string">""</span><span class="hljs-string">"
"</span>To be or not to be<span class="hljs-string">" is a quote from Shakespeare's Hamlet.
"</span><span class="hljs-string">""</span>;
Console.WriteLine(text);
<span class="hljs-comment">// Output: "To be or not to be" is a quote from Shakespeare’s Hamlet.</span>
</code></pre>
<p>Note the output of the code example depicted in figure 16.</p>
<p>Figure 16.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">string</span> path = <span class="hljs-string">""</span><span class="hljs-string">"C:\development\CSharpProjects"</span><span class="hljs-string">""</span>;
Console.WriteLine(path);
<span class="hljs-comment">// Output: C:\development\CSharpProjects</span>
</code></pre>
<p>You could output the multiline text shown in the code example in figure 17, where the output is displayed to the screen in much the same way as the text is represented over multiple lines in the relevant raw literal string in code.</p>
<p>Note that when using a raw string literal to output multiple lines of text, the three double quote characters that must be used to wrap the relevant multiline text must each be on their own line, as is depicted in the example in figure 17.</p>
<p>Figure 17.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">string</span> narrative = <span class="hljs-string">""</span><span class="hljs-string">"
Humpty Dumpty sat on the wall
Humpty Dumpty had a great fall
all the kings horses and all the kings men
couldn’t put Humpty together again
"</span><span class="hljs-string">""</span>;
</code></pre>
<h2 id="heading-useful-c-built-in-string-methods">Useful C# Built-in String Methods</h2>
<p>The C# language has many useful built-in string methods that can, for example, be leveraged for common string-related functionality.</p>
<h3 id="heading-the-indexof-built-in-method">The IndexOf Built-in Method</h3>
<p>One common example is finding a string literal within text stored within a string variable using the <code>IndexOf</code> method. See the code example of this depicted in figure 18.</p>
<p>Figure 18.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> narrative = <span class="hljs-string">"Gavin Lon loves to create free courses on the freeCodeCamp YouTube channel."</span>;

<span class="hljs-comment">// find freeCodeCamp in the narrative</span>
<span class="hljs-keyword">var</span> indx = narrative.IndexOf(<span class="hljs-string">"freeCodeCamp"</span>);

<span class="hljs-comment">// the value of indx will be 46</span>
<span class="hljs-keyword">if</span> (indx == <span class="hljs-number">-1</span>)
{
    Console.WriteLine(<span class="hljs-string">"\"freeCodeCamp\" could not be found in the narrative"</span>);
}
<span class="hljs-keyword">else</span>
{
    Console.WriteLine(<span class="hljs-string">$"\"freeCodeCamp\" was found at position <span class="hljs-subst">{indx}</span> in the narrative"</span>);
}
indx = narrative.IndexOf(<span class="hljs-string">"Gavin Lon"</span>);

<span class="hljs-comment">// the value of indx will be 0</span>
<span class="hljs-keyword">if</span> (indx == <span class="hljs-number">-1</span>)
{
    Console.WriteLine(<span class="hljs-string">"\"Gavin Lon\" could not be found in the narrative"</span>);
}
<span class="hljs-keyword">else</span>
{
    Console.WriteLine(<span class="hljs-string">$"\"Gavin Lon\" was found at position <span class="hljs-subst">{indx}</span>"</span>);
}
<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// "freeCodeCamp" was found at position 46 in the narrative</span>
<span class="hljs-comment">// "Gavin Lon" was found at position 0</span>
</code></pre>
<h3 id="heading-the-replace-built-in-method">The Replace Built-in Method</h3>
<p>Another example of common string related functionality used in C# is finding a specific literal string value within text stored in a variable and replacing the relevant literal string with another literal string value. You can do this in C# using the builtin <code>Replace</code> method.</p>
<p>Check out the code example showing this in figure 19.</p>
<p>Figure 19.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> narrative = <span class="hljs-string">"Gavin Lon loves to create free courses on the freeCodeCamp YouTube channel."</span>;
<span class="hljs-keyword">var</span> newNarrative = narrative.Replace(<span class="hljs-string">"Gavin Lon"</span>, <span class="hljs-string">"Farhan Hassan Chowdury"</span>);
Console.WriteLine(newNarrative);
<span class="hljs-comment">// Output: Farhan Hassan Chowdury loves to create free courses on the freeCodeCamp YouTube channel.</span>
</code></pre>
<h3 id="heading-the-substring-built-in-method">The Substring Built-in Method</h3>
<p>Another common example is assigning a portion of text stored within a variable to another variable using the builtin <code>Substring</code> method. Here's a code example depicting this in figure 20.</p>
<p>Figure 20.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> narrative = <span class="hljs-string">"Gavin Lon loves to create free courses on the freeCodeCamp YouTube channel."</span>;
<span class="hljs-keyword">var</span> charityName = narrative.Substring(<span class="hljs-number">46</span>, <span class="hljs-number">12</span>);
Console.WriteLine(charityName);
<span class="hljs-comment">// Output: freeCodeCamp</span>
</code></pre>
<p>You can also watch the YouTube video below for more information and code examples that talk about using and manipulating strings in C#.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/tzJjrrOe69c" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-c-data-type-conversion">C# Data Type Conversion</h2>
<p>As we discussed above, in C#, variables are statically typed at compile time. This means that once a variable has been defined as a specific type, you can’t define the variable again and you can’t assign a value of an incompatible data type to a variable.</p>
<p>Have a look at the example depicted in figure 21 that highlights static typing in C#.</p>
<p>Figure 21.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">string</span> narrative = <span class="hljs-string">"The cat sat on the mat."</span>;
narrative = <span class="hljs-number">1</span> + <span class="hljs-number">1</span>; <span class="hljs-comment">// Compile time error: "Cannot implicitly convert type 'int' to 'string'"</span>
</code></pre>
<p>Here's an example of what happens if you attempt to define a variable twice in code:</p>
<p>Figure 22.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">int</span> a = <span class="hljs-number">1</span>;
<span class="hljs-keyword">string</span> a = <span class="hljs-string">"one"</span>;
<span class="hljs-comment">// The compiler would immediately flag an error and underline the ‘a’ variable, where an attempt to</span>
<span class="hljs-comment">// define variable, a, as string is made.</span>
<span class="hljs-comment">// A compile time error occurs: "A local variable or function named 'a' is already defined in this scope"</span>
</code></pre>
<h3 id="heading-implicit-vs-explicit-data-type-conversion">Implicit vs Explicit Data Type Conversion</h3>
<p>Variables defined as numeric datatypes can be implicitly converted to certain other numeric datatypes – but in other cases an explicit conversion is required.</p>
<p>Implicit data type conversion means that the compiler will automatically convert a variable defined as one data type to another data type, and you don't need to appropriately implement explicit data type conversion code in order for the appropriate data type conversion to occur.</p>
<p>The following code example in figure 23 demonstrates trying to implicitly convert a variable defined as a short integer to the byte data type. Note the commented lines that explain what happens in your code editor.</p>
<p>Figure 23.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">short</span> b = <span class="hljs-number">255</span>;
<span class="hljs-keyword">byte</span> a = b;
<span class="hljs-comment">// The compiler would immediately flag an exception and a red squiggly line would appear under</span>
<span class="hljs-comment">// variable b in the second line of code.</span>
<span class="hljs-comment">// If you hover your mouse pointer over the red squiggly line the following error message is</span>
<span class="hljs-comment">// presented: “Cannot implicitly convert type ‘short’ to ‘byte’. An explicit conversion exists (are you missing a cast?)”</span>
</code></pre>
<p>After reading the commented lines in figure 23, you can see that an explicit conversion is required to satisfy the C# compiler.</p>
<p>The code in figure 24 shows how you can use an explicit type conversion in this case to prevent the relevant data type compile time exception from being flagged.</p>
<p>Figure 24.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">short</span> b = <span class="hljs-number">255</span>;
<span class="hljs-keyword">byte</span> a = Convert.ToByte(b);
Console.Write(b);
<span class="hljs-comment">// When this code runs, 255, is printed to the console screen</span>
</code></pre>
<p>It's important to note that an explicit type conversion can result in a runtime error occurring. If you assigned <code>b</code> with a value of <code>256</code> instead of <code>255</code> (as in the code depicted in figure 24), a run time error would occur when the code is run.</p>
<p>So this explicit type conversion is dangerous because, in this case, the erroneous code would not be flagged at compile time – which would have forced you to fix the error at compile time (before the code is released into production). So this code would result in a runtime error occuring.</p>
<p>The error is caused because the byte data type supports storing whole number values in memory from <code>0</code> to <code>255</code>. A value of <code>256</code> is clearly outside of this range, so a runtime error will occur with the following error message, <code>System.OverFlowException: Value was either too large or too small for an unsigned byte.</code>. So a value of <code>256</code> must be stored in a variable defined with a data type that supports a range that is greater than the range supported by the byte data type.</p>
<p>The next data type in C# that supports a greater range than the byte data type for whole number values is the short integer data type (or short data type). The value range that a short data type supports is from <code>-32,768</code> to <code>32,767</code>.</p>
<p>The variable defined as the short data type would be clearly be appropriate for storing a whole number value of <code>256</code>.</p>
<p>The next data type that supports a greater value range for whole numbers (than the short data type) is the int data type. The int data type supports a value range from <code>-2,147,483,648</code> to <code>2,147,483,647</code>.</p>
<p>The data type that supports the greatest value range for whole numbers is the long data type, which supports values from <code>-9,223,372,036,854,775,808</code> to <code>9,223,372,036,854,775,807</code>.</p>
<p>As we have just discussed, the C# language has data types like the byte data type, the short data type, the int data type and the long datatype for defining variables for the purpose of storing whole number values.</p>
<p>In C#, there are built-in data types appropriate for the storage of values that contain fractal values. Three data types that you can use for the definition of variables for the storage of values with fractal parts are the float, double, and decimal data type.</p>
<p>A great example of a type of value where you’d want to use one of these data types to define a variable (for storing a value that contains a fractal part) is the decimal data type used for storing monetary values. You could use the float or the double data type for storing monetary values, but the decimal data type is more appropriate for this scenario. This is because the decimal data type (although supports less magnitude than the float or double data types) supports greater precision.</p>
<p>In a banking application, for example, where monetary value precision is of the utmost importance, accounting for fractions of value is essential. So the decimal data type (that supports the highest precision for values in C#) should be leveraged for storing monetary values.</p>
<p>Keep in mind that data can be lost when converting a value stored in a variable defined as one particular data type to another data type.</p>
<p>For example, if you have a monetary value stored in a variable defined as a decimal data type that contains a fractal part, converting this value to, for e.g. an int data type would result in the loss of the fractal part of the value.</p>
<p>Here's an example of this depicted in figure 25.</p>
<p>Figure 25</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> monetaryValue = <span class="hljs-number">10.34</span>m; <span class="hljs-comment">// note if the ‘m’ suffix is not provided the data type is</span>

<span class="hljs-comment">// assumed to be the double data type.</span>
<span class="hljs-comment">// The ‘m’ suffix explicitly defines the variable as</span>
<span class="hljs-comment">// decimal</span>
<span class="hljs-keyword">var</span> <span class="hljs-keyword">value</span> = Decimal.ToInt32(monetaryValue); <span class="hljs-comment">//converts decimal to int</span>
Console.WriteLine(<span class="hljs-keyword">value</span>); <span class="hljs-comment">// this outputs 10 – the value of 0.34 is lost</span>
</code></pre>
<p>So you can see that a value of <code>0.34</code> would be lost as a result of running the data type conversion code depicted in figure 25.</p>
<p>You can check out the YouTube video below for more information on implicit and explicit data type conversions in C#.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/NF4lyA1yx8Y" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-c-operators">C# Operators</h2>
<p>C# operators are made up of one or more symbols that signify to the C# compiler that a particular operation should be performed between relevant operands.</p>
<p>In figure 26, we have a few simple examples of built-in C# operators used to perform mathematical operations.</p>
<p>Figure 26.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> a = <span class="hljs-number">1</span>;
<span class="hljs-keyword">var</span> b = <span class="hljs-number">2</span>;
<span class="hljs-keyword">var</span> r = a + b; <span class="hljs-comment">// the ‘+’ symbol signifies to the compiler to perform an appropriate Addition operation</span>
Console.WriteLine(r); <span class="hljs-comment">// prints 3 to the screen</span>
r = a * <span class="hljs-number">2</span>; <span class="hljs-comment">//the ‘*’ symbol signifies to the compiler to perform an appropriate multiplication operation</span>
Console.WriteLine(r); <span class="hljs-comment">//prints 2 to the screen</span>
r = b - a; <span class="hljs-comment">//the ‘-’ symbol signifies to the compiler to perform an appropriate subtraction operation</span>
Console.WriteLine(r); <span class="hljs-comment">// prints 1 to the screen</span>
r = b / <span class="hljs-number">2</span>; <span class="hljs-comment">//the ‘/’ symbol signifies to the compiler to perform an appropriate multiplication operation</span>
Console.WriteLine(r); <span class="hljs-comment">// prints 1 to the screen</span>
</code></pre>
<p>Typically you are able to overload the default behaviour for built-in operators for numeric data types in C#. So you can change the behaviour of specific operators between two operands defined as specific built-in C# data types.</p>
<p>In the above example, the <code>+</code> operator performs an addition mathematical operation between the relevant operands. You could write code to overload the <code>+</code> operator and change the default addition functionality between two integers.</p>
<p>For example, instead of performing an addition operation between <code>1</code> and <code>2</code> where a value of <code>3</code> is the result of the relevant operation, your operator overload code could return <code>12</code>. So in this case the <code>1</code> and <code>2</code> are simply put together as if a concatenation of two string values was being performed. An integer value of <code>12</code> would be the result of the relevant operation.</p>
<p>Of course, overloading the operator in this way may not be very practical. This example merely illustrates how you could change the behaviour of the <code>+</code> operator between two integer values by overloading the <code>+</code> operator in C#.</p>
<h3 id="heading-types-of-c-operators">Types of C# Operators</h3>
<p>The table below is copied from the Microsoft Learn platform at this URL, <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators">https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators</a></p>
<table>
<thead>
<tr>
<th>Operators</th>
<th>Category or name</th>
</tr>
</thead>
<tbody>
<tr>
<td><a href="member-access-operators#member-access-expression-">x.y</a>, <a href="member-access-operators#invocation-expression-">f(x)</a>, <a href="member-access-operators#indexer-operator-">a[i]</a>, <a href="member-access-operators#null-conditional-operators--and-"><code>x?.y</code></a>, <a href="member-access-operators#null-conditional-operators--and-"><code>x?[y]</code></a>, <a href="arithmetic-operators#increment-operator-">x++</a>, <a href="arithmetic-operators#decrement-operator---">x--</a>, <a href="null-forgiving">x!</a>, <a href="new-operator">new</a>, <a href="type-testing-and-cast#typeof-operator">typeof</a>, <a href="../statements/checked-and-unchecked">checked</a>, <a href="../statements/checked-and-unchecked">unchecked</a>, <a href="default">default</a>, <a href="nameof">nameof</a>, <a href="delegate-operator">delegate</a>, <a href="sizeof">sizeof</a>, <a href="stackalloc">stackalloc</a>, <a href="pointer-related-operators#pointer-member-access-operator--">x-&gt;y</a></td>
<td>Primary</td>
</tr>
<tr>
<td><a href="arithmetic-operators#unary-plus-and-minus-operators">+x</a>, <a href="arithmetic-operators#unary-plus-and-minus-operators">-x</a>, <a href="boolean-logical-operators#logical-negation-operator-">!x</a>, <a href="bitwise-and-shift-operators#bitwise-complement-operator-">~x</a>, <a href="arithmetic-operators#increment-operator-">++x</a>, <a href="arithmetic-operators#decrement-operator---">--x</a>, <a href="member-access-operators#index-from-end-operator-">^x</a>, <a href="type-testing-and-cast#cast-expression">(T)x</a>, <a href="await">await</a>, <a href="pointer-related-operators#address-of-operator-">&amp;x</a>, <a href="pointer-related-operators#pointer-indirection-operator-"><em>x</em></a>, <a href="true-false-operators">true and false</a></td>
<td>Unary</td>
</tr>
<tr>
<td><a href="member-access-operators#range-operator-">x..y</a></td>
<td>Range</td>
</tr>
<tr>
<td><a href="switch-expression">switch</a>, <a href="with-expression">with</a></td>
<td><code>switch</code> and <code>with</code> expressions</td>
</tr>
<tr>
<td><a href="arithmetic-operators#multiplication-operator-">x  y</a>, <a href="arithmetic-operators#division-operator-">x / y</a>, <a href="arithmetic-operators#remainder-operator-">x % y</a></td>
<td>Multiplicative</td>
</tr>
<tr>
<td><a href="arithmetic-operators#addition-operator-">x + y</a>, <a href="arithmetic-operators#subtraction-operator--">x – y</a></td>
<td>Additive</td>
</tr>
<tr>
<td><a href="bitwise-and-shift-operators#left-shift-operator-">x &lt;&lt;  y</a>, <a href="bitwise-and-shift-operators#right-shift-operator-">x &gt;&gt; y</a>, <a href="bitwise-and-shift-operators#unsigned-right-shift-operator-">x &gt;&gt;&gt; y</a></td>
<td>Shift</td>
</tr>
<tr>
<td><a href="comparison-operators#less-than-operator-">x &lt; y</a>, <a href="comparison-operators#greater-than-operator-">x &gt; y</a>, <a href="comparison-operators#less-than-or-equal-operator-">x &lt;= y</a>, <a href="comparison-operators#greater-than-or-equal-operator-">x &gt;= y</a>, <a href="type-testing-and-cast#is-operator">is</a>, <a href="type-testing-and-cast#as-operator">as</a></td>
<td>Relational and type-testing</td>
</tr>
<tr>
<td><a href="equality-operators#equality-operator-">x == y</a>, <a href="equality-operators#inequality-operator-">x != y</a></td>
<td>Equality</td>
</tr>
<tr>
<td><code>x &amp; y</code></td>
<td><a href="boolean-logical-operators#logical-and-operator-">Boolean logical AND</a> or <a href="bitwise-and-shift-operators#logical-and-operator-">bitwise logical AND</a></td>
</tr>
<tr>
<td><code>x ^ y</code></td>
<td><a href="boolean-logical-operators#logical-exclusive-or-operator-">Boolean logical XOR</a> or <a href="bitwise-and-shift-operators#logical-exclusive-or-operator-">bitwise logical XOR</a></td>
</tr>
<tr>
<td><code>x | y</code></td>
<td><a href="boolean-logical-operators#logical-or-operator-">Boolean logical OR</a> or <a href="bitwise-and-shift-operators#logical-or-operator-">bitwise logical OR</a></td>
</tr>
<tr>
<td><a href="boolean-logical-operators#conditional-logical-and-operator-">x &amp;&amp; y</a></td>
<td>Conditional AND</td>
</tr>
<tr>
<td><a href="boolean-logical-operators#conditional-logical-or-operator-">x || y</a></td>
<td>Conditional OR</td>
</tr>
<tr>
<td><a href="null-coalescing-operator">x ?? y</a></td>
<td>Null-coalescing operator</td>
</tr>
<tr>
<td><a href="conditional-operator">c ? t : f</a></td>
<td>Conditional operator</td>
</tr>
<tr>
<td><a href="assignment-operator">x = y</a>, <a href="arithmetic-operators#compound-assignment">x += y</a>, <a href="arithmetic-operators#compound-assignment">x -= y</a>, <a href="arithmetic-operators#compound-assignment">x *= y</a>, <a href="arithmetic-operators#compound-assignment">x /= y</a>, <a href="arithmetic-operators#compound-assignment">x %= y</a>, <a href="boolean-logical-operators#compound-assignment">x &amp;= y</a>, <a href="boolean-logical-operators#compound-assignment">x |= y</a>, <a href="boolean-logical-operators#compound-assignment">x ^= y</a>, <a href="bitwise-and-shift-operators#compound-assignment">x &lt;&lt;= y</a>, <a href="bitwise-and-shift-operators#compound-assignment">x &gt;&gt;= y</a>, <a href="bitwise-and-shift-operators#compound-assignment">x &gt;&gt;&gt;= y</a>, <a href="null-coalescing-operator">x ??= y</a>, <a href="lambda-operator">=&gt;</a></td>
<td>Assignment and lambda declaration</td>
</tr>
</tbody>
</table>


<p>For more information on C# Operators, you can watch the YouTube Video below:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/qGgwm95FK5M" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>For instructions on how you can overload operators in C#, check out the following YouTube video:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/tq3_8GQxM14" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-constants-and-read-only-variables">Constants and Read-only Variables</h2>
<h3 id="heading-introduction-to-constants">Introduction to Constants</h3>
<p>A constant is like a variable in the sense that you can store a value in it by declaring it and assigning it a value. You can then reference that value with a human readable name that denotes the const value in code.</p>
<p>A constant is different from a variable in the sense that it must be assigned a value on the same line in which it is declared. Also, once you have assigned a value to a constant, you cannot assign a new value to that constant at any other point in the code.</p>
<p>You should use constants in your code where they make your code more readable and maintainable. When you appropriately use a const, you don’t have to repeat a value that you assigned to the const in your code. When you need to reference that value in code, you can instead include the human readable name you gave the const in your code that denotes the relevant constant value.</p>
<p>If a const value needs to change, you only need to change the code in one place (that is where the const has been declared). This change will automatically propagate to where the constant is referenced in other lines of code (that are appropriately scoped).</p>
<h3 id="heading-introduction-to-read-only-variables">Introduction to Read-only Variables</h3>
<p>A read-only variable is like a variable in that you can store a value in it by declaring it and assigning it a value. You can then reference that value with a human readable name that denotes the read-only variable.</p>
<p>A read-only variable is different from a variable in that its value can only be changed once in code after it has been declared. Its value can be changed in the constructor of a class, but cannot be changed in other parts of your code.</p>
<p>So if you have assigned a read-only variable with a value in the line where it's declared, you can assign that read-only variable with a different value in the constructor of a class – but you can't then assign that read-only variable a new value in any other code.</p>
<p>So a read-only variable is often referred to as a runtime constant. A constant is declared and assigned its value on the same line of code at compile time, and the value for that const cannot be subsequently changed at compile time (and so also can’t be changed at runtime).</p>
<p>A read-only variable is assigned the value that cannot be subsequently changed at runtime. So with a read-only variable, where it is assigned a value within the constructor of a class, is set once when an object instance is created from that class at runtime. That read-only variable cannot be changed after this assignment is made.</p>
<h3 id="heading-code-example-using-a-const">Code Example Using a Const</h3>
<p>Here's an example of how to use a const depicted in figure 27.</p>
<p>Figure 27.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">const</span> <span class="hljs-keyword">int</span> SpeedOfLight = <span class="hljs-number">299792458</span>;
Console.WriteLine(<span class="hljs-string">$"The speed of light is <span class="hljs-subst">{SpeedOfLight}</span>"</span>);
<span class="hljs-comment">// The output for this code is:</span>
<span class="hljs-comment">// The speed of light is 299792458</span>
</code></pre>
<h3 id="heading-code-example-using-a-read-only-variable">Code Example Using a Read-only Variable</h3>
<p>And here's an example in figure 28 of how to use a read-only variable:</p>
<p>Figure 28.</p>
<pre><code class="lang-csharp">Employee employee = <span class="hljs-keyword">new</span> Employee(<span class="hljs-string">"Admin"</span>);
employee.PrintEmployeeRole();
</code></pre>
<p>Notice how the read-only string variable named <code>"RoleName"</code> has been assigned a value twice. It's assigned an empty string when it's first declared at the top of the class. The read-only variable is assigned its final value within the constructor of the <code>Employee</code> class.</p>
<p>Note that you can only change the value of a read-only variable once, and you can only do this within the constructor of a class. Once a read-only variable’s value is assigned within the constructor of a class, you can't change its value in any other part of the code.</p>
<p>In the example below in figure 29, a method named <code>SetRoleName</code> contains code to change the value of the <code>RoleName</code> read-only variable. This is not possible in C#, because the read-only variable can only be assigned its final value within the contructor of a class. You cannot for e.g. assign the read-only variable a value within a method.</p>
<p>This code will result in a compile time error being flagged by the C# compiler. The error message will state the following in your code editor: <code>A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initialiser)</code>.</p>
<h3 id="heading-code-example-of-the-incorrect-use-of-a-read-only-variable">Code Example of the Incorrect Use of a Read-only Variable</h3>
<p>Figure 29.</p>
<pre><code class="lang-csharp">Employee employee = <span class="hljs-keyword">new</span> Employee(<span class="hljs-string">"Admin"</span>);
employee.PrintEmployeeRole();
</code></pre>
<p>For more information on const and read-only variables, you can watch the YouTube video below:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/yvOdN5PBY2g" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-c-if-else-if-else-statements">C# if / else if / else Statements</h2>
<h3 id="heading-basic-ifelse-conditional-logic">Basic if/else Conditional Logic</h3>
<p>If statements allow you to include conditional logic in your code. Let's look at a basic example to see how they work.</p>
<p>Let's say you are working on a shopping cart application and a particular piece of code adds a product to the user's shopping cart. In your code, you only want that item added to the user’s shopping cart if the product is in stock.</p>
<p>When a user tries to add a product that is out of stock, you want a message displayed informing the user that the item they want to add is not in stock. You could also add to this message that they should try to add this item to their shopping cart in a week (i.e. when the item may be in stock).</p>
<p>In C#, to automate this conditional logic, you can implement an <code>if / else</code> statement. The code in figure 30 shows how this might look:</p>
<pre><code class="lang-csharp">Product product = <span class="hljs-keyword">new</span>();
product.Name = <span class="hljs-string">"Ladder"</span>;
product.ItemCount = <span class="hljs-number">10</span>;
<span class="hljs-keyword">if</span> (product.ItemCount == <span class="hljs-number">0</span>)
{
    DisplayMessage(<span class="hljs-string">$"<span class="hljs-subst">{product.Name}</span> is currently not in stock. Please try again in a week."</span>);
}
<span class="hljs-keyword">else</span>
{
    AddToShopingCart(product);
    DisplayMessage(<span class="hljs-string">$"A <span class="hljs-subst">{product.Name}</span> has been successfully added to your shopping cart."</span>);
}
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">DisplayMessage</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> message</span>)</span>
{
    Console.WriteLine(message);
}
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">AddToShopingCart</span>(<span class="hljs-params">Product product</span>)</span>
{
    Console.WriteLine(<span class="hljs-string">"Code runs to add product"</span>);
}

<span class="hljs-keyword">class</span> <span class="hljs-title">Product</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Name { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; } = <span class="hljs-string">""</span>;
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> ItemCount { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
}
</code></pre>
<p>The <code>if</code> statement contains a boolean expression. A boolean expression returns either <code>true</code> or <code>false</code>. If the product is in stock, this boolean expression, <code>product.ItemCount == 0</code>, will return <code>false</code>. If the product is not in stock, then the boolean expression will return <code>true</code>.</p>
<p>The <code>if</code> statement expression evaluates whether the relevant product is currently in stock. If the relevant product is no longer in stock, the <code>ItemCount</code> property will return <code>0</code>. In the case, where the number of products in stock is equal to <code>0</code>, code runs and tells the user that the product is not in stock and that they should try to add the product to their cart in a week.</p>
<p>If, however, the count of stock for the product is not equal to <code>0</code> (meaning the product is in stock), code will run that adds the product to the user's shopping cart. A message will also appear on the user's screen stating that the product has been successfully added to the user's shopping cart.</p>
<p>You can simply include an <code>if</code> statement on its own – and not include an <code>else</code> block within the relevant conditional logic. For example, let's say you wanted to output a message to people using a banking application. When their account is overdrawn (that is, they've taken out too much money), the code might look like the basic example in figure 31:</p>
<p>Figure 31.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">decimal</span> currentAccountValue = <span class="hljs-number">1000</span>m;
<span class="hljs-keyword">decimal</span> withdrawalAmount = <span class="hljs-number">2000</span>m;
<span class="hljs-keyword">var</span> balance = currentAccountValue - withdrawalAmount;
<span class="hljs-keyword">if</span> (balance &lt; <span class="hljs-number">0</span>)
{
    DisplayMessage(<span class="hljs-string">"Your account is overdrawn."</span>); <span class="hljs-comment">// this message will be displayed to the user</span>
}
</code></pre>
<h3 id="heading-implementing-ifelse-ifelse-conditional-logic">Implementing if/else if/else Conditional Logic</h3>
<p>Let’s say that in addition to the above code logic, we want to add a requirement so that a specific message is displayed to the person if they can successfully make a withdrawal without their account being overdrawn.</p>
<p>In this requirement, we also want to include a message that gets displayed if their withdrawal results in the balance being less than <code>100</code> dollars.</p>
<p>To account for these additional requirements, we can update the relevant conditional logic with an <code>else if</code> block and an <code>else</code> block. The code in figure 32 shows how this code might look.</p>
<p>Figure 32.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">decimal</span> currentAccountValue = <span class="hljs-number">1000</span>m;
<span class="hljs-keyword">decimal</span> withdrawalAmount = <span class="hljs-number">876</span>m;
<span class="hljs-keyword">var</span> balance = currentAccountValue - withdrawalAmount;
<span class="hljs-keyword">if</span> (balance &lt; <span class="hljs-number">0</span>)
{
    DisplayMessage(<span class="hljs-string">"Your account is overdrawn."</span>);
}
<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (balance &lt; <span class="hljs-number">100</span>)
{
    DisplayMessage(<span class="hljs-string">"You have less than 100 dollars left in your account."</span>);
}
<span class="hljs-keyword">else</span>
{
    DisplayMessage(<span class="hljs-string">$"You have successfully withdrawn <span class="hljs-subst">{withdrawalAmount}</span> dollars"</span>);
}
</code></pre>
<p>So how does the <code>if/else if/ else</code> code work? The first boolean expression is evaluated which accounts for if the balance is less than <code>0</code>. If this expression returns <code>true</code>, the message, <code>"Your account is overdrawn."</code>, is displayed to the user.</p>
<p>If that expression returns <code>false</code>, the code in the <code>else if</code> block is evaluated, and then the expression is evaluated to check if the balance is less than <code>100</code>. If this expression returns <code>true</code> (that is, if the value of <code>balance</code> is less than <code>100</code>) the message , <code>"You have less than 100 dollars left in your account."</code>&gt;, is displayed to the user.</p>
<p>If however, the expression returns <code>false</code>, this means that the code within the <code>else</code> block is executed. So the message, <code>"You have successfully withdrawn {withdrawalAmount} dollars"</code> is displayed to the screen.</p>
<p>Each expression is evaluated from top to bottom and each section of the <code>if/else if/else</code> code is mutually exclusive. This means that only one of the statements within each of the sections of the <code>if/else if/else</code> logic can be run when the relevant conditional logic is executed.</p>
<p>When this conditional logic is run, only one of the messages will be displayed to the user as a result of them making a withdrawal from their account.</p>
<h3 id="heading-nested-if-statements">Nested if Statements</h3>
<p>You can also include nested if statements within your conditional logic. An example of this is depicted in figure 33.</p>
<p>Figure 33.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">decimal</span> currentAccountValue = <span class="hljs-number">1000</span>m;
<span class="hljs-keyword">decimal</span> withdrawalAmount = <span class="hljs-number">6500</span>m;
<span class="hljs-keyword">var</span> balance = currentAccountValue - withdrawalAmount;
<span class="hljs-keyword">if</span> (balance &lt; <span class="hljs-number">0</span>)
{
    <span class="hljs-keyword">if</span> (balance &lt; <span class="hljs-number">-5000</span>)
    {
        DisplayMessage(
            <span class="hljs-string">"You have reached your allowable overdraft limit. You will be charged a penalty amount!"</span>
        );
    }
    <span class="hljs-keyword">else</span>
    {
        DisplayMessage(<span class="hljs-string">"Your account is overdrawn."</span>);
    }
}
<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (balance &lt; <span class="hljs-number">100</span>)
{
    DisplayMessage(<span class="hljs-string">"You have less than 100 dollars left in your account."</span>);
}
<span class="hljs-keyword">else</span>
{
    DisplayMessage(<span class="hljs-string">$"You have successfully withdrawn <span class="hljs-subst">{withdrawalAmount}</span> dollars"</span>);
}
</code></pre>
<p>In the above example, the top <code>if</code> statement first checks to see if the account has been overdrawn. If the account has been overdrawn (that is, the value of <code>balance</code> is less than <code>0</code>), a nested <code>if/else</code> statement runs. A nested <code>if</code> statement is an <code>if</code> statement that resides within another <code>if</code> statement.</p>
<p>The nested <code>if</code> statement only runs if the expression in the <code>if</code>statement in which the nested <code>if</code> statement resides returns <code>true</code>.</p>
<p>The nested <code>if</code> statement depicted in figure 33 further evaluates if the balance is less than <code>-5000</code>. If this expression returns <code>true</code>, then the user sees a message informing them that the amount just drawn from their account has resulted in the account being overdrawn (i.e. in excess of their allowable overdraft amount). It also lets the user know that the user will be charged an additional penalty amount.</p>
<p>The code in the <code>else</code> part of the nested <code>if</code> statement runs if the user’s balance is between <code>-5000</code> and <code>0</code>. This means their account is overdrawn but will not, in this case, result in a penalty amount being charged (because it's within their allowable overdraft limit).</p>
<h3 id="heading-more-complex-conditional-expressions">More Complex Conditional Expressions</h3>
<h4 id="heading-the-ampamp-operator">The &amp;&amp; Operator</h4>
<p>An <code>if</code> statement can include more complex boolean logic as well. For example, you can use the <code>&amp;&amp;</code> operator or the <code>||</code> operator to evaluate multiple boolean expressions on one line. Figure 34 below depicts a code example of using the <code>&amp;&amp;</code> operator in an <code>if</code> statement to evaluate more than one boolean expression on one line.</p>
<p>The <code>&amp;&amp;</code> operator can be translated as "And also". If the first expression on the left side of the <code>&amp;&amp;</code> operator is evaluated as <code>false</code>, this means that the entire boolean expression evaluated by the <code>if</code> statement is deemed <code>false</code>. The boolean expression on the right side of the expression is not evaluated.</p>
<p>In this case, <code>false</code> is returned by the <code>if</code> statement, meaning that the code within the <code>if</code> statements will not be run.</p>
<p>But if, in this example, the condition on the left hand side of the <code>&amp;&amp;</code> operator is <code>true</code>, this means that the expression on the right side of the <code>&amp;&amp;</code> operator must be evaluated. So in this case, if the value of <code>balance</code> is less than <code>-5000</code>, the boolean expression returns <code>false</code>. This means that the entire boolean expression <code>(balance &lt; -4000 &amp;&amp; balance &gt;= -5000)</code> is <code>false</code>. This also means that the message displayed by the code within the <code>if</code> statement will not run.</p>
<p>But if the code on the right side of the <code>&amp;&amp;</code> operator is <code>true</code> (so in this case the balance is greater than or equal to <code>-5000</code>), the entire boolean expression in the <code>if</code> statement is <code>true</code>. This means the message in the <code>if</code> statement will be outputted to the screen. So <code>Your transaction is successful but you are close to your overdraft limit</code> will be outputted to the screen.</p>
<p>Figure 34.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">decimal</span> currentAccountValue = <span class="hljs-number">1000</span>m;
<span class="hljs-keyword">decimal</span> withdrawalAmount = <span class="hljs-number">5500</span>m;
<span class="hljs-keyword">var</span> balance = currentAccountValue - withdrawalAmount;
</code></pre>
<h4 id="heading-the-operator">The || Operator</h4>
<p>You can also use the <code>||</code> operator (as shown in figure 35) when appropriate for boolean expressions that consist of more than one boolean expression.</p>
<p>The <code>||</code> operator can be translated as "or-else". When the boolean expression on the left side of the <code>||</code> operator returns <code>true</code>, the boolean expression on the right side of the <code>||</code> operator does not need to be evaluated. This is because only one of the expressions needs to return true for the entire boolean expression to return <code>true</code>.</p>
<p>If the boolean expression on the left of the <code>||</code> operator returns <code>false</code>, then the expression on the right will be evaluated.</p>
<p>If the expression on the right returns <code>false</code>, then the entire expression returns <code>false</code>. If, however, the expression on the right of the <code>||</code> operator returns <code>true</code>, the entire boolean expression returns <code>true</code>.</p>
<p>Figure 35.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">decimal</span> currentAccountValue = <span class="hljs-number">1000</span>m;
<span class="hljs-keyword">decimal</span> withdrawalAmount = <span class="hljs-number">960</span>m;
<span class="hljs-keyword">var</span> balance = currentAccountValue - withdrawalAmount;
<span class="hljs-keyword">if</span> (withdrawalAmount &lt; <span class="hljs-number">50</span> || balance &lt; <span class="hljs-number">-5000</span>)
{
    RollBackTransaction();
    DisplayMessage(
        <span class="hljs-string">"Your transaction failed either because you tried to withdraw less than 50 dollars or your total withdrawal would have resulted in your account having a balance of less than -5000 dollars which exceeds your overdraft limit."</span>
    );
}
<span class="hljs-keyword">else</span>
{
    DisplayMessage(<span class="hljs-string">"Thank you! Your transaction was successful!"</span>);
    CommitTransaction();
}
</code></pre>
<p>The code in figure 35 evaluates the boolean expression in the <code>if</code> statement as, if the withdrawl amount is less than 50 dollars then rollback the transaction and display the appropriate message. If, however, the withdrawl amount is greater than 50 dollars the expression on the right hand side of the <code>||</code> operator needs to be evaluated because this means that the expression on the left hand side of the <code>||</code> operator has returned <code>false</code>.</p>
<p>So if the expression on the right hand side of the <code>||</code> operator returns <code>true</code> meaning that the customer's <code>balance</code> is less than <code>-5000</code>, the code to rollback the transaction and display the appropriate message must be run.</p>
<p>So the key take away when using the <code>||</code> operator in an <code>if</code> condition is that if one of the expressions on either side of the <code>||</code> operator returns true, this means that the entire condition returns <code>true</code>. In order for the entire condition to return <code>false</code>, both expressions on either side of the <code>||</code> operator must return <code>false</code>.</p>
<p>So if both expressions on either side of the <code>||</code> operator returns <code>false</code>, this means that the customer has made a valid withdrawl, and the customer's transaction proceeds successfully. A message to this effect is displayed to the customer as a result.</p>
<p>Here's a comprehensive explanation of using <code>if</code> statements for conditional logic in C# in the YouTube video below:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/2mChNV9GmpM" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-c-loops">C# Loops</h2>
<h3 id="heading-the-for-loop">The for Loop</h3>
<p>Through the use of loops in code, programmers are able to drastically reduce the lines of code required to perform specific tasks. A very simple example of this is displaying a count from <code>1</code> to <code>10</code> where each value is printed on a new line in the console window. Without using a loop the code could look like the code depicted in figure 36.</p>
<p>Figure 36.</p>
<pre><code class="lang-csharp">Console.WriteLine(<span class="hljs-string">"1"</span>);
Console.WriteLine(<span class="hljs-string">"2"</span>);
Console.WriteLine(<span class="hljs-string">"3"</span>);
Console.WriteLine(<span class="hljs-string">"4"</span>);
Console.WriteLine(<span class="hljs-string">"5"</span>);
Console.WriteLine(<span class="hljs-string">"6"</span>);
Console.WriteLine(<span class="hljs-string">"7"</span>);
Console.WriteLine(<span class="hljs-string">"8"</span>);
Console.WriteLine(<span class="hljs-string">"9"</span>);
Console.WriteLine(<span class="hljs-string">"10"</span>);
</code></pre>
<p>Using a <code>for</code> loop in C# you could reduce 10 lines of code to 3 lines of code as is depicted in figure 37. You could update the code so that the <code>for</code> loop loops 100 times instead of 10 times. To do this you would change the relevant <code>for</code> loop expression from, <code>count&lt;=10</code>, to <code>count &lt;=100</code>. So in the code example depicted in figure 38 you would have reduced 100 lines of code to 3 lines of code by using the <code>for</code> loop to achieve exactly the same output.</p>
<p>Figure 37.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> count = <span class="hljs-number">1</span>; count &lt;= <span class="hljs-number">10</span>; count++)
{
    Console.WriteLine(count);
}
</code></pre>
<p>Figure 38.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> count = <span class="hljs-number">1</span>; count &lt;= <span class="hljs-number">100</span>; count++)
{
    Console.WriteLine(count);
}
</code></pre>
<p>You could implement the same functionality using a <code>while</code> loop that loops 10 times as is depicted in figure 39.</p>
<h3 id="heading-the-while-loop">The while Loop</h3>
<p>Figure 39.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> count = <span class="hljs-number">1</span>;
</code></pre>
<h3 id="heading-the-do-while-loop">The do-while Loop</h3>
<p>You could implement the same functionality using a <code>do-while</code> loop in C# as is depicted in figure 40.</p>
<p>Figure 40.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> count = <span class="hljs-number">1</span>;
<span class="hljs-keyword">do</span>
{
    Console.WriteLine(count);
    count++;
} <span class="hljs-keyword">while</span> (count &lt;= <span class="hljs-number">10</span>);
</code></pre>
<p>The difference between a <code>while</code> loop and a <code>do-while</code> loop is that a <code>do-while</code> loop will always execute the code within it at least once. With a <code>while</code> loop the boolean conditional expression is at the top of the loop so when this expression returns <code>false</code> (i.e. before code within the <code>while</code> loop has a chance to run), no code within the <code>while</code> loop will run. With the <code>do-while</code> loop, code within the <code>do-while</code> loop is always executed at least once. In the example depicted in Figure 41, the statements within the <code>while</code> block will never run.</p>
<p>Figure 41.</p>
<p>The value of <code>count</code> is equal to <code>11</code> and the boolean conditional expression, <code>(count &lt;= 10)</code>, returns <code>false</code> so the two lines of code within the <code>while</code> loop will not execute. Let's look at a similar example but where a <code>do-while</code> loop is used. This example is depicted in figure 42.</p>
<p>Figure 42.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> count = <span class="hljs-number">11</span>;
<span class="hljs-keyword">do</span>
{
    Console.WriteLine(count);
    count++;
} <span class="hljs-keyword">while</span> (count &lt;= <span class="hljs-number">10</span>);
</code></pre>
<p>The lines of code within the <code>do-while</code> loop will execute one time. So the result of this is the value of <code>11</code> will be printed to the console screen. After the value of <code>11</code> is printed to the console screen, the boolean expression, <code>(count &lt;= 10)</code>, is run. The value of <code>count</code> is <code>11</code> which means the boolean expression at the bottom of the <code>do-while</code> loop returns <code>false</code>, so the loop will be exited.</p>
<h3 id="heading-the-foreach-loop">The foreach Loop</h3>
<p>In C# you can leverage a <code>foreach</code> loop instead of a <code>for</code> loop. One of the advantages of using a <code>foreach</code> loop rather than a <code>for</code> loop is that if the number of traversals that need to occur in order to traverse all of the relevant items in the loop change, the code created for the execution of the loop does not need to change. Consider this example depicted in figure 43 where a <code>foreach</code> loop is used to print each value contained within an array to the console screen.</p>
<p>Figure 43.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">int</span>[] arr = { <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">10</span> };
<span class="hljs-keyword">foreach</span> (<span class="hljs-keyword">var</span> val <span class="hljs-keyword">in</span> arr)
{
    Console.Write(<span class="hljs-string">$"<span class="hljs-subst">{val}</span> "</span>);
}
<span class="hljs-comment">// Output:  1 2 3 4 5 6 7 8 9 10</span>
</code></pre>
<p>Consider what happens when the number of items and values in the array are changed. Please see a code example depiciting this in figure 44.</p>
<p>Figure 44.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">int</span>[] arr = { <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">10</span>, <span class="hljs-number">11</span>, <span class="hljs-number">13</span>, <span class="hljs-number">12</span> };
<span class="hljs-keyword">foreach</span> (<span class="hljs-keyword">var</span> val <span class="hljs-keyword">in</span> arr)
{
    Console.Write(<span class="hljs-string">$"<span class="hljs-subst">{val}</span> "</span>);
}
<span class="hljs-comment">// Output:  1 2 3 4 5 6 7 8 9 10 11 13 12</span>
</code></pre>
<p>A <code>for</code> loop used to execute the same code would look like the code example depicted in figure 45.</p>
<p>Figure 45.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">int</span>[] arr = { <span class="hljs-number">10</span>, <span class="hljs-number">8</span>, <span class="hljs-number">5</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">4</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">3</span>, <span class="hljs-number">11</span>, <span class="hljs-number">13</span>, <span class="hljs-number">12</span> };
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> x = <span class="hljs-number">0</span>; x &lt;= arr.Length - <span class="hljs-number">1</span>; x++)
{
    Console.Write(<span class="hljs-string">$"<span class="hljs-subst">{arr[x]}</span> "</span>);
}
<span class="hljs-comment">// Output: 10 8 5 1 2 6 7 4 8 9 3 11 13 12</span>
</code></pre>
<p>With the <code>for</code> loop, the length of the array must be included in the code for executing the loop. The index of the array must be included in the code where each item is printed to the screen. You can accomplish the same task using a <code>for</code> loop and a <code>foreach</code> loop in these scenarios but the <code>foreach</code> loop is cleaner and easier to read. So with the <code>foreach</code> loop you don’t have to worry about the index of the elements in the array or the length of the array.</p>
<p>For more details on loops in C# and more code examples, please watch the YouTube video below this paragraph.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/oO0GXIIE56U" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-c-arrays">C# Arrays</h2>
<p>An array is a data structure. You can store multiple values of the same type within an array. You can also store multiple types within an array by defining the array elements as the object data type.</p>
<p>All types in C# inherit from the object data type, so you can store multiple types of data within an array where the elements are defined as objects.</p>
<p>Consider the below example depicted in figure 46 where an integer array is defined that can store 10 integer values.</p>
<p>Figure 46.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">int</span>[] arrValues = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">10</span>];
</code></pre>
<p>In this example, the array can only store integer values. If you try to store any other type in this array, an appropriate compile time error will be flagged.</p>
<p>In the next example in figure 47, you can only store string values.</p>
<p>Figure 47.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">string</span>[] arrayStringValues = <span class="hljs-keyword">new</span> <span class="hljs-keyword">string</span>[<span class="hljs-number">10</span>];
</code></pre>
<p>But in the example depicted in figure 48 below, you can store both string and integer values as well as other types of data in the array. This is because, as discussed, all data types in C# inherit from the object data type. So in the array in the example below, you can store string values, integer values, decimal values, boolean values, char values, user defined typed values, and so on.</p>
<p>Figure 48.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">object</span>[] arrayObjectValues = <span class="hljs-keyword">new</span> <span class="hljs-keyword">object</span>[<span class="hljs-number">10</span>];
</code></pre>
<p>Storing multiple data types in this way this is known as 'boxing', because, for example, if an integer is stored as an element within an array defined as object, the integer data is first ‘boxed’ within the object type. This means that in order to retrieve the data as its appropriate data type from the array, the value must first be ‘unboxed’. This simply means that the relevant array element is explicitly type cast from an object to its appropriate data type.</p>
<p>It is important to note that when defining an array as an object, you are in effect circumventing the type system of the C# language and losing the benefits of a strongly typed language (like faster performance, as well as increased robustness of runtime code).</p>
<p>The 'unboxing' code that needs to run when retrieving values from the array can potentially cause runtime errors to occur, as well as causes a casting runtime overhead. And this slows down the performance of the code.</p>
<p>So strongly typing the array is recommended to increase runtime performance and runtime robustness. This lets you leverage the benefits of the strong type system supported by the C# language.</p>
<h3 id="heading-one-dimensional-arrays">One-dimensional Arrays</h3>
<p>In C# you have three types of arrays, one dimensional arrays, multi-dimensional arrays, and jagged arrays.</p>
<p>A one dimensional array allows for the storage of data that is one dimensional in nature. An example of this would be an array of grades for a particular student for a particular year.</p>
<p>So for example, let's say that a student received the following grades in 2023: 60, 50, 72, 85, 91. These grades could be stored in a one dimensional integer array like is depicted in figure 49.</p>
<p>Figure 49.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">int</span>[] grades = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">5</span>]{<span class="hljs-number">60</span>, <span class="hljs-number">50</span>, <span class="hljs-number">72</span>, <span class="hljs-number">85</span>, <span class="hljs-number">91</span>};
</code></pre>
<h3 id="heading-multi-dimensional-arrays">Multi-dimensional Arrays</h3>
<h4 id="heading-two-dimensional-arrays">Two-dimensional Arrays</h4>
<p>An example of using a multi-dimensional array could be an array where more than one student’s grades are stored in the array. This code example is depicted in below figure 50.</p>
<p>So lets say that grades for Sarah, John, and Bob are stored within the two dimensional array. Within the main set of curley brackets, all of the values are included in the two dimensional array. Also within the main set of curly brackets are three sets of curly brackets, one set for each student. And within each of the three sets of curly brackets are 5 grades pertaining to the three students.</p>
<p>So lets say the first set of grades belongs to Sarah, the second set of grades belongs to John, and the third set of grades belongs to Bob.</p>
<p>Figure 50.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">int</span>[,] studentGrades = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">3</span>, <span class="hljs-number">5</span>]
{
    { <span class="hljs-number">60</span>, <span class="hljs-number">50</span>, <span class="hljs-number">72</span>, <span class="hljs-number">85</span>, <span class="hljs-number">91</span> },
    { <span class="hljs-number">50</span>, <span class="hljs-number">45</span>, <span class="hljs-number">67</span>, <span class="hljs-number">80</span>, <span class="hljs-number">93</span> },
    { <span class="hljs-number">48</span>, <span class="hljs-number">58</span>, <span class="hljs-number">90</span>, <span class="hljs-number">57</span>, <span class="hljs-number">87</span> }
};
</code></pre>
<p>So the first subscript in the array is 3, which in this example represents the number of students. The second subscript in the array represents the number of grades. So you could use a C# nested <code>for</code> loop to loop through the items in this array and print their values to the screen in a two dimensional matrix display.</p>
<p>In figure 51 you'll see an example of looping through a two dimensional array and displaying the results to the console screen in a two dimensional matrix.</p>
<p>Figure 51.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">int</span>[,] studentGrades = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">3</span>, <span class="hljs-number">5</span>]
{
    { <span class="hljs-number">60</span>, <span class="hljs-number">50</span>, <span class="hljs-number">72</span>, <span class="hljs-number">85</span>, <span class="hljs-number">91</span> },
    { <span class="hljs-number">50</span>, <span class="hljs-number">45</span>, <span class="hljs-number">67</span>, <span class="hljs-number">80</span>, <span class="hljs-number">93</span> },
    { <span class="hljs-number">48</span>, <span class="hljs-number">58</span>, <span class="hljs-number">90</span>, <span class="hljs-number">57</span>, <span class="hljs-number">87</span> }
};
</code></pre>
<h4 id="heading-three-dimensional-arrays">Three-dimensional Arrays</h4>
<p>You could add another dimension to this array – for example, you could split the grades up for each student so the grades relate to a particular time of year.</p>
<p>For simplicity, let's divide the year in half. So for the first half of 2023, Sarah received the following grades: 54, 42, 70, 80, 93. For the second half of the year, Sarah received the these grades: 65, 46, 68, 90, 95.</p>
<p>So in this example (depicted in figure 52), the relevant three dimensional array includes the results for Sarah and two other students (John and bob) where their results include their grades for the first half of 2023 as well as their grades for the second half of 2023.</p>
<p>Figure 52.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">int</span>[,,] studentGrades = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">3</span>, <span class="hljs-number">2</span>, <span class="hljs-number">5</span>]
{
    {
        { <span class="hljs-number">60</span>, <span class="hljs-number">50</span>, <span class="hljs-number">72</span>, <span class="hljs-number">85</span>, <span class="hljs-number">91</span> },
        { <span class="hljs-number">65</span>, <span class="hljs-number">46</span>, <span class="hljs-number">68</span>, <span class="hljs-number">90</span>, <span class="hljs-number">95</span> }
    },
    {
        { <span class="hljs-number">45</span>, <span class="hljs-number">40</span>, <span class="hljs-number">64</span>, <span class="hljs-number">70</span>, <span class="hljs-number">90</span> },
        { <span class="hljs-number">55</span>, <span class="hljs-number">50</span>, <span class="hljs-number">73</span>, <span class="hljs-number">90</span>, <span class="hljs-number">95</span> }
    },
    {
        { <span class="hljs-number">46</span>, <span class="hljs-number">60</span>, <span class="hljs-number">88</span>, <span class="hljs-number">55</span>, <span class="hljs-number">89</span> },
        { <span class="hljs-number">50</span>, <span class="hljs-number">56</span>, <span class="hljs-number">92</span>, <span class="hljs-number">59</span>, <span class="hljs-number">85</span> }
    }
};
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; studentGrades.GetLength(<span class="hljs-number">0</span>); i++)
{
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> j = <span class="hljs-number">0</span>; j &lt; studentGrades.GetLength(<span class="hljs-number">1</span>); j++)
    {
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> k = <span class="hljs-number">0</span>; k &lt; studentGrades.GetLength(<span class="hljs-number">2</span>); k++)
        {
            Console.Write(<span class="hljs-string">$"<span class="hljs-subst">{studentGrades[i, j, k]}</span>\t"</span>);
        }
        Console.WriteLine();
    }
    Console.WriteLine();
    Console.WriteLine();
}
</code></pre>
<p>So in figure 52 above, you can see the first student’s data is printed to the console screen where the first line presents the student’s grades for the first half of the year.</p>
<p>This is followed by a line feed and the first student’s grades for the second half of the year are printed on the subsequent line. Two line feeds follow the data printed for the first student. This is followed by the second student’s grades, and so on.</p>
<p>The first dimension of the array is in this case denoted by the three students. The second dimension of the array is in this case denoted by the the parts of the year (in this case the year is divided into 2 parts (or two halves)). The third dimension of the array is denoted by the actual grades for each student (in this case, five grades).</p>
<p>So depicted in Figure 52 is an example of a three dimensional array declared and initialised. The code that follows outputs the values stored in the three dimensional array to the console screen. So the example in figure 52 is a great example of C# code that implements nested for loops to print out the data stored in a 3 dimensional array to the console screen.</p>
<p>So with this example, you are in effect printing out three dimensional data onto a 2 dimensional screen using C#.</p>
<h3 id="heading-jagged-arrays">Jagged Arrays</h3>
<p>Basically a Jagged array is an array of arrays. It allows you to store uneven data (if you like).</p>
<p>So what do I mean by uneven data? If you go back to the 2-dimensional array example depicted in figure 51, you have 5 grades represented for each of the three students.</p>
<p>Let’s say that student number two (John in the example) studies only the first three subjects, so you only have grades for those three subjects for John. But you have five grades pertaining to the first three subjects as well as grades pertaining to the last two subjects for the other two students (Sarah and Bob) completed. You still want to store John’s three grades along with the five grades for Sarah and Bob in the array.</p>
<p>Well, good news - you can store all of the data (without the need to include redundant ‘placeholder’ data for John’s missing two grades) by using a jagged array.</p>
<p>In the example depicted in figure 53, C# code is implemented for storing the relevant grades in a jagged array. The code that follows outputs the grades to the console screen.</p>
<p>Figure 53.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">int</span>[][] studentGrades = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">3</span>][];
studentGrades[<span class="hljs-number">0</span>] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">5</span>] { <span class="hljs-number">60</span>, <span class="hljs-number">50</span>, <span class="hljs-number">72</span>, <span class="hljs-number">85</span>, <span class="hljs-number">91</span> }; <span class="hljs-comment">// Sarah’s grades</span>
studentGrades[<span class="hljs-number">1</span>] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">3</span>] { <span class="hljs-number">50</span>, <span class="hljs-number">45</span>, <span class="hljs-number">67</span> }; <span class="hljs-comment">// John’s grades</span>
studentGrades[<span class="hljs-number">2</span>] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">5</span>] { <span class="hljs-number">48</span>, <span class="hljs-number">58</span>, <span class="hljs-number">90</span>, <span class="hljs-number">57</span>, <span class="hljs-number">87</span> }; <span class="hljs-comment">// Bob’s grades</span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; studentGrades.Length; i++)
{
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> j = <span class="hljs-number">0</span>; j &lt; studentGrades[i].Length; j++)
    {
        Console.Write(<span class="hljs-string">$"<span class="hljs-subst">{studentGrades[i][j]}</span>\t"</span>);
    }
    Console.WriteLine();
}
</code></pre>
<p>You can see by the outputted results, that when compared to the output in the two dimensional array example depicted in figure 51, the shape of the data is jagged (uneven). This is why this data structure is referred to as a jagged array.</p>
<p>You can watch the YouTube video below for more information on arrays in C#, as well as more code examples of how arrays are used in C# code.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/K4wjL7kRJyE" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-c-methods">C# Methods</h2>
<h3 id="heading-introduction-to-methods-in-c">Introduction to Methods in C</h3>
<p>A method is simply a block of code that contains a series of statements. When a program is run and a method is called, the statements within that method are executed.</p>
<p>In C#, every statement is executed in the context of a method. So methods are fundamental to how C# code is structured and executed.</p>
<h3 id="heading-the-main-method">The Main Method</h3>
<p>The <code>Main</code> method is the entry point of all C# applications. So this is the method that is first executed whenever a program coded in C# is run.</p>
<p>The CLR (Common Language Runtime) calls the <code>Main</code> method when a program (coded in C#) is first started. In C# you can create both named methods and anonymous methods. In this part of the C# book, we'll discuss named methods.</p>
<h3 id="heading-the-structure-of-methods">The Structure of Methods</h3>
<p>Methods are used to encapsulate a series of statements that get executed when the method is called in code. In some cases, a method is just a series of statements where (at runtime) the statements are executed in sequence and no value is returned from the relevant method to the calling code.</p>
<p>These methods (that don’t return a value) contain the <code>void</code> keyword in the relevant method declaration to signify that the method does not return a value.</p>
<p>Methods can also be created that contain a list of statements that are executed sequentially. At the end of the list of statements, a value of a specified data type is returned to the calling code.</p>
<p>For methods that return values, the data type denoting the value that must be returned from the method is appropriately included within the method's declaration. At the end of the sequence of statements encapsulated by the method, the <code>return</code> keyword is included, followed by the value that will be returned to the calling code, on the same line as where the <code>return</code> keyword is included.</p>
<p>You can see a simple example of a method that is used for returning the result of a mathematical operation in figure 54.</p>
<p>Figure 54.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">int</span> result = AddTwoNumbers(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>);
Console.WriteLine(result);
<span class="hljs-keyword">int</span> result2 = AddTwoNumbers(<span class="hljs-number">300</span>, <span class="hljs-number">400</span>);
Console.WriteLine(result2);
</code></pre>
<p>In the example above, this simple method has a method declaration that contains a <code>private</code> access modifier. This means that the <code>AddTwoNumbers</code> method is only accessible from methods contained within the same class in which the <code>AddTwoNumbers</code> method resides.</p>
<p>The <code>AddTwoNumbers</code> method returns a value that is of type integer. This is denoted by the <code>int</code> alias used in the method declaration.</p>
<p>The method declaration contains two parameters, both of the integer data type. The first line of code within the method executes the addition mathematical operation between two arguments that are appropriately passed to the method’s parameters at runtime. The second line of code within the method uses the <code>return</code> C# keyword followed by the result of the previous statement, to return the result of the relvant mathematical operation to the calling code.</p>
<p>The <code>return</code> keyword denotes returning a value to the calling code, which in this case will be the result of the mathematical operation executed in the first line of code within the <code>AddTwoNumbers</code> method.</p>
<p>In the example below (depicted in figure 55), two statements are contained within the method. A fundamental difference between the <code>AddTwoNumbers</code> method (depicted in figure 54) and the method below (depicted in Figure 55) is that the <code>LogFormulaResultToFile</code> method (depicted in figure 55) does not return a value. This is denoted by the <code>void</code> keyword which is included within the <code>LogFormulaResultToFile</code> method declaration.</p>
<p>Figure 55.</p>
<pre><code class="lang-csharp">LogFormulaResultToFile(<span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-string">"This is the result: "</span>);

<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// This is the result:  7</span>

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">LogFormulaResultToFile</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> operand1, <span class="hljs-keyword">int</span> operand2, <span class="hljs-keyword">string</span> message</span>)</span>
{
    <span class="hljs-keyword">int</span> result = operand1 + operand2;
    LogToFile(<span class="hljs-string">$"<span class="hljs-subst">{message}</span> <span class="hljs-subst">{result}</span>"</span>);
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">LogToFile</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> message</span>)</span>
{
    Console.WriteLine(message); <span class="hljs-comment">// for simplicity print message to screen rather than write to file</span>
}
</code></pre>
<p>The fundamental structure for every method in C# is defined by its method signature. And we’ve discussed that within methods are a series of statements.</p>
<p>The method signature defines what type of value is returned by the method, the name of the method, and the level of access (or scope) associated with the method (for example, <code>private</code> or <code>public</code>). The method signature also includes zero, one, or a list of parameters denoting arguments that can be passed to the method when the method is called at runtime. The method signature can also contain the following keywords, <code>abstract</code>,<code>sealed</code>, or <code>virtual</code>. These keywords are beyond the scope of this handbook.</p>
<p>Methods are declared in a <code>class</code>, <code>struct</code> or <code>interface</code>. Methods in an <code>interface</code> do not contain any implementation (that is, any statements) and only the method signature is defined in an <code>interface</code>.</p>
<p>Note that methods defined within an <code>interface</code> do not include access modifiers. When a <code>class</code> implements an <code>interface</code>, the methods contained within the <code>interface</code> must be appropriately implemented by the <code>class</code> that implements the <code>interface</code>.</p>
<p>On the other hand, when methods are contained within a <code>class</code> or a <code>struct</code>, both the method signatures and code implementations for the methods are included.</p>
<p>The example below (depicted in figure 56) demonstrates the implementation of a <code>public</code> method that can be used to return the factorial of a number.</p>
<p>Figure 56.</p>
<pre><code class="lang-csharp">MathFunctions mathFunctions = <span class="hljs-keyword">new</span> MathFunctions();
<span class="hljs-keyword">var</span> result = mathFunctions.GetFactorial(<span class="hljs-number">6</span>);
Console.WriteLine(result);

<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// 720</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">MathFunctions</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">GetFactorial</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> num</span>)</span>
    {
        <span class="hljs-keyword">int</span> fact = <span class="hljs-number">1</span>;
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>; i &lt;= num; i++)
        {
            fact = fact * i;
        }
        <span class="hljs-keyword">return</span> fact;
    }
}
</code></pre>
<p>In the <code>public</code> method named, <code>GetFactorial</code>, a local variable is declared and initialised to a value of <code>1</code> at the top of the method.</p>
<p>A local variable is a variable that has local scope, meaning that in this case the <code>fact</code> variable is not accessible outside of the <code>GetFactorial</code> method. It is only accessible within the <code>GetFactorial</code> method. This means that the <code>fact</code> variable’s value cannot be changed from outside the method but can only be changed from within the method.</p>
<p>You can see that within the <code>for</code> loop, a statement is run that alters the value of the <code>fact</code> variable with each iteration of the loop. Once the the loop is terminated, a final result is reached and that result is returned (using the C# <code>return</code> keyword) to the calling code.</p>
<p>If for example the <code>GetFactorial</code> method resides within a class named, <code>MathFunctions</code>, the calling code could look like the example below depicted in figure 57.</p>
<p>Figure 57.</p>
<pre><code class="lang-csharp">
MathFunctions mathFunctions = <span class="hljs-keyword">new</span> MathFunctions();
<span class="hljs-keyword">var</span> result = mathFunctions.GetFactorial(<span class="hljs-number">6</span>);
Console.WriteLine(result);
</code></pre>
<p>Below, you'll see an example of a <code>private</code> method that uses C# string manipulation to appropriately concatenate and reformat the string arguments representing the first name and last name of an employee (depicted in figure 58).</p>
<p>So if the employee’s first name is "John" and the employee's last name is "Denver", the relevant method will return the string value, "Denver, J". The method concatenates the last name with a comma followed by the a further concatenation of the first initial of the employee’s first name.</p>
<p>This concatenation operation is presented by the <code>return</code> keyword on the same line, which means the result of the concatenation operation is returned to the calling code.</p>
<p>Figure 58.</p>
<pre><code class="lang-csharp"><span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">string</span> <span class="hljs-title">FormatName</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> firstName, <span class="hljs-keyword">string</span> lastName</span>)</span>
{
    <span class="hljs-keyword">return</span> lastName + <span class="hljs-string">", "</span> + firstName.Substring(<span class="hljs-number">0</span>, <span class="hljs-number">1</span>).ToUpper();
}
</code></pre>
<p>In figure 59 below, we have a code sample where a class named <code>Employee</code> is included. This class contains a read-only property named, <code>DisplayName</code>. This property exposes the formatted <code>name</code> to the calling code through the use of the <code>public</code> access modifier.</p>
<p>The <code>firstName</code> and <code>lastName</code> string arguments are passed to the constructor of the <code>Employee</code> class when it is instantiated by the calling code. The calling code can then write the relevant employee’s formatted name to the console screen. So the <code>private</code> method, <code>FormatName</code>, is not accessible to the calling code. The formatting of the employee's name is handled within the <code>Employee</code> class.</p>
<p>This is a design decision driven by the requirements.</p>
<p>Figure 59.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Employee</span>
{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">string</span> firstName = <span class="hljs-string">""</span>;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">string</span> lastName = <span class="hljs-string">""</span>;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Employee</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> firstName, <span class="hljs-keyword">string</span> lastName</span>)</span>
    {
        <span class="hljs-keyword">this</span>.firstName = firstName;
        <span class="hljs-keyword">this</span>.lastName = lastName;
    }

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> DisplayName
    {
        <span class="hljs-keyword">get</span> { <span class="hljs-keyword">return</span> FormatName(<span class="hljs-keyword">this</span>.firstName, <span class="hljs-keyword">this</span>.lastName); }
    }

    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">string</span> <span class="hljs-title">FormatName</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> firstName, <span class="hljs-keyword">string</span> lastName</span>)</span>
    {
        <span class="hljs-keyword">return</span> lastName + <span class="hljs-string">", "</span> + firstName.Substring(<span class="hljs-number">0</span>, <span class="hljs-number">1</span>).ToUpper();
    }
}
</code></pre>
<p>The calling code could look like the code example depicted in figure 60:</p>
<p>Figure 60.</p>
<pre><code class="lang-csharp">Employee employee = <span class="hljs-keyword">new</span> Employee(<span class="hljs-string">"John"</span>, <span class="hljs-string">"Denver"</span>);
Console.WriteLine(employee.DisplayName);
<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// Denver, J</span>
</code></pre>
<p>The code example depicted in figure 59 demonstrates the use of the code design concept of encapsulation. The complexity of the <code>FormatName</code> functionality is encapsulated within a <code>private</code> method in the <code>Employee</code> class so the calling code is not concerned with the implementation detail of the formatting functionality of the employee’s name. The calling code only needs to reference the <code>DisplayName</code> property on an object derived from the <code>Employee</code> user defined type (or class). The formatting functionality is handled within the <code>Employee</code> class.</p>
<p>The <code>private</code> access modifier enforces the encapsulation of the formatting functionality. The <code>FormatName</code> method is not accessible from the calling code, but is only accessible from within the <code>Employee</code> class.</p>
<p>This particular design decision is enforced through the use of the <code>private</code> access modifier appropriately contained within the <code>FormatName</code> method declaration.</p>
<h2 id="heading-c-classes">C# Classes</h2>
<p>C# supports object-oriented programming. All data types including user defined types in C# inherit from the <code>object</code> data type, so you could say that everything in C# is an object. So an <code>int</code> is an object, a <code>decimal</code> is an object, a <code>string</code> is an object, a <code>bool</code> is an object etc…</p>
<p>The main difference between an <code>int</code>, <code>decimal</code> and <code>bool</code> when compared to a <code>string</code> data type is that the <code>int</code>, <code>decimal</code> and <code>bool</code> data types inherit from the ValueType abstract class, the ValueType class in turn inserts from the <code>object</code> type. This means that the <code>int</code>, <code>decimal</code> and <code>bool</code> data types are value types. Strings, on the other hand are reference types. The <code>string</code> data type does not inherit from the ValueType abstract class but inherits directly from <code>System.Object</code> class.</p>
<p>Note that <code>int</code>, <code>bool</code> and <code>decimal</code> data types are implemented as structs in C#. Structs are value types and are similar to classes in many ways.</p>
<p>The main difference between a struct and a class in C# is that structs are value types and classes are reference types. The <code>string</code> data type inherits directly form the <code>System.Object</code> type which means the <code>string</code> datatype is a reference type.</p>
<p>In C# you are able to create your own custom classes. When you create a class in C#, behind the scenes your user defined type inherits from the <code>System.Object</code> type. So your user defined class is a reference type.</p>
<p>Note that you can also create user defined structs using the <code>struct</code> keyword, whereas when you create user defined classes, you use the <code>class</code> keyword.</p>
<p>The underlying difference between a class and a struct is the way they are stored in memory. Value types store their data directly in a memory location known as the stack, while reference types store a numeric reference (memory address) on the stack, to an object containing the actual data (where the data is actually stored) known as the heap.</p>
<p>The stack stores data in a more structured way than how data is stored on the heap. Make sure you understand this difference, because it affects how the objects derived from classes or structs are copied and passed around in code, and the efficiency with which data is stored and retreived in memory.</p>
<p>Structs are generally faster than classes, so if you are working with large amounts of data, structs may be a more efficient option because they don’t require the overhead of heap memory. Structs may be the best option when needing to represent a simple data structure that contains  data types like integer, boolean, or decimal datatypes.</p>
<p>Structs also have the benefit of being handled more efficiently in memory, which means when dealing with large amounts of instantiated objects from a particular data structure, a struct may be a better option to represent that data, rather than a class.</p>
<p>Structs and classes are both similar in that they both support concepts like for example constructors, fields, properties and methods.</p>
<p>In figure 61 the <code>Player</code> class is used as a template for an object that represents a game object for a particular game.</p>
<p>Figure 61</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Player</span>
{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">string</span> name = <span class="hljs-string">""</span>;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Player</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> name</span>)</span>
    {
        <span class="hljs-keyword">this</span>.name = name;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Move</span>(<span class="hljs-params"><span class="hljs-keyword">double</span> x, <span class="hljs-keyword">double</span> y</span>)</span>
    {
        Console.WriteLine(<span class="hljs-string">$"Moving <span class="hljs-subst">{name}</span> to coordinates where 'x' = <span class="hljs-subst">{x}</span>, and 'y' = <span class="hljs-subst">{y}</span>"</span>);
    }
}
</code></pre>
<p>In the above example (depicted in figure 61), you can see some of the fundamental concepts in C# being expressed, through for example the use of the <code>class</code> keyword, the <code>private</code> and public access modifiers, a constructor that contains one parameter, a method that contains two parameters and a private member variable defined as a string.</p>
<h3 id="heading-the-class-keyword">The class keyword</h3>
<p>The class keyword in C# is used for defining a user defined reference type or class.</p>
<h3 id="heading-the-public-access-modifier">The Public Access Modifier</h3>
<p>Preceding the <code>class</code> keyword is the <code>public</code> access modifier. The use of the <code>public</code> access modifier in this way means that this class can be accessed and instantiated from anywhere within the assembly in which the class resides as well as from outside of the assembly in which the class resides.</p>
<h3 id="heading-the-private-member-variable">The Private Member Variable</h3>
<p>The <code>private</code> member variable named, <code>name</code>, is not directly accessible to code that exists outside of the <code>Player</code> class. The <code>name</code> member variable can only be accessed and used from within a property, constructor or method that resides within the <code>Player</code> class.</p>
<h3 id="heading-the-constructor">The Constructor</h3>
<p>The <code>Player</code> class (depicted in the code example in figure 61) has one constructor. Classes are instantiated into objects at runtime. The Player constructor contains one string parameter named <code>name</code>. When calling code instantiates an object derived from the <code>Player</code> class, the name of the <code>Player</code> can be passed as an argument to the Player objects constructor.</p>
<p>Within the constructor of the ‘Player’ class the private member variable named, <code>name</code> is assigned the value passed in by calling code to the parameterised constructor of the ‘Player’ class. When the calling code subsequently calls the <code>Move</code> method, the <code>name</code> member variable is accessed and utilised by code within the <code>Move</code> method. The constructor is called when the object is derived from the <code>Player</code> class.</p>
<p>The constructor enables the calling code to assign a value for the name of the player pertaining to the relevant object at the point at which the relevant object is instantiated.</p>
<h3 id="heading-the-move-method">The Move Method</h3>
<p>Once the calling code has instantiated an object from the <code>Player</code> class, the calling code is able to execute the code within the Move method by appropriately calling the <code>Move</code> method on the relevant object.</p>
<p>The <code>Move</code> method is accessible to code from outside of the class in which it resides because it has a <code>public</code> access modifier. If the method had, for example, a private access modifier, this method would only be accessible from within the class in which it resides.</p>
<p>When the <code>Move</code> method is executed by calling code, two arguments of type <code>double</code>, must be passed into the move method because the <code>Move</code> method contains two parameters of type <code>double</code>.</p>
<p>Below (in figure 62) is an example of calling code instantiating an object from the <code>Player</code> class and subsequently calling the Move method on the relevant instantiated player object.</p>
<p>Figure 62.</p>
<pre><code class="lang-csharp">Player player = <span class="hljs-keyword">new</span> Player(<span class="hljs-string">"Bob"</span>);
player.Move(<span class="hljs-number">10.54</span>, <span class="hljs-number">18.43</span>);
</code></pre>
<p>For more information on C# Classes please view the video below:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/6rlUl5T2Sck" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>And below you can find a full video series on C# classes:</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=6rlUl5T2Sck&amp;list=PL4LFuHwItvKY76WTDhfGAwrpLZaSxF9fS">C# Classes Video Series</a></p>
<h2 id="heading-c-structs">C# Structs</h2>
<p>The <code>struct</code> keyword is used to define a data structure in C# that is a value type. Structs are similar to classes in many respects – for example, you can use both structs and classes to represent data structures that can contain data members and related behavioural functionality expressed within methods.</p>
<h3 id="heading-key-differences-between-a-class-and-a-struct">Key differences between a Class and a Struct.</h3>
<ul>
<li>The main difference is that a class is a reference type and a struct is a value type. Structs implicitly inherit from the <code>System.ValueType</code> abstract class (which in turn inherits from the <code>System.Object</code> class), while reference types inherit directly from the <code>System.Object</code> type.</li>
<li>A struct is a better choice than a class when representing data structures that store small amounts of data. Another good reason to use a struct is if you need to store small amounts of data in the relevant data structure and where a vast number of objects derived from the relevant struct are being dealt with in code.</li>
<li>You can instantiate an object from a struct using the <code>new</code> keyword just like you would when instantiating an object from a class. But the <code>new</code> keyword is not required when declaring and initialising a struct before you can use it in code.</li>
<li>In C# certain value type primitives are represented as structs, for example the <code>int</code> alias represents the <code>System.Int32</code> struct, the <code>bool</code> alias represents the <code>System.Bool</code> struct, and the <code>float</code> alias represents <code>System.Single</code> struct.</li>
</ul>
<h3 id="heading-use-a-struct-in-code">Use a Struct in Code</h3>
<p>Below (depicted in figure 63) is an example of code that uses a struct to store the specifications for a pattern. The pattern is denoted by a circle that is drawn within a square.</p>
<p>The <code>Radius</code> field stores the value that denotes the radius of the circle, which also determines the size of the square. The <code>InnerSymbol</code> field denotes the <code>char</code> value printed to the screen that is used for depicting the inner circle. The <code>OuterSymbol</code> field denotes the <code>char</code> value printed to the screen that is used for depicting the outer square in the overall pattern.</p>
<p>Figure 63.</p>
<pre><code class="lang-csharp">Console.WriteLine(<span class="hljs-string">"Please enter the radius of the circle"</span>);
<span class="hljs-keyword">double</span> radius = Convert.ToDouble(Console.ReadLine());

CircleInSquare circleInSquare;
circleInSquare.Radius = radius;
circleInSquare.InnerSymbol = <span class="hljs-string">'0'</span>;
circleInSquare.OuterSymbol = <span class="hljs-string">'1'</span>;
circleInSquare.Draw();

<span class="hljs-comment">//Output</span>

<span class="hljs-comment">// 11111111111111111111111111111111111111111</span>
<span class="hljs-comment">// 11111111111111000000000000011111111111111</span>
<span class="hljs-comment">// 11111111110000000000000000000001111111111</span>
<span class="hljs-comment">// 11111111000000000000000000000000011111111</span>
<span class="hljs-comment">// 11111100000000000000000000000000000111111</span>
<span class="hljs-comment">// 11110000000000000000000000000000000001111</span>
<span class="hljs-comment">// 11100000000000000000000000000000000000111</span>
<span class="hljs-comment">// 11000000000000000000000000000000000000011</span>
<span class="hljs-comment">// 11000000000000000000000000000000000000011</span>
<span class="hljs-comment">// 11000000000000000000000000000000000000011</span>
<span class="hljs-comment">// 11000000000000000000000000000000000000011</span>
<span class="hljs-comment">// 11000000000000000000000000000000000000011</span>
<span class="hljs-comment">// 11000000000000000000000000000000000000011</span>
<span class="hljs-comment">// 11000000000000000000000000000000000000011</span>
<span class="hljs-comment">// 11100000000000000000000000000000000000111</span>
<span class="hljs-comment">// 11110000000000000000000000000000000001111</span>
<span class="hljs-comment">// 11111100000000000000000000000000000111111</span>
<span class="hljs-comment">// 11111111000000000000000000000000011111111</span>
<span class="hljs-comment">// 11111111110000000000000000000001111111111</span>
<span class="hljs-comment">// 11111111111111000000000000011111111111111</span>
<span class="hljs-comment">// 11111111111111111111111111111111111111111</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">struct</span> CircleInSquare
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">double</span> Radius;
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">char</span> InnerSymbol;
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">char</span> OuterSymbol;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">CircleInSquare</span>(<span class="hljs-params"><span class="hljs-keyword">double</span> radius, <span class="hljs-keyword">char</span> innerSymbol, <span class="hljs-keyword">char</span> outerSymbol</span>)</span>
    {
        Radius = radius;
        InnerSymbol = innerSymbol;
        OuterSymbol = outerSymbol;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">WriteMemberValuesToScreen</span>(<span class="hljs-params"></span>)</span>
    {
        Console.WriteLine(
            <span class="hljs-string">$"Radius = <span class="hljs-subst">{Radius}</span>, InnerSymbol = '<span class="hljs-subst">{InnerSymbol}</span>', OuterSymbol = '<span class="hljs-subst">{OuterSymbol}</span>'"</span>
        );
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Draw</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-keyword">double</span> radiusInner = Radius - <span class="hljs-number">0.5</span>;
        <span class="hljs-keyword">double</span> radiusOuter = Radius + <span class="hljs-number">0.5</span>;

        Console.WriteLine();

        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">double</span> y = Radius; y &gt;= -Radius; --y)
        {
            <span class="hljs-keyword">for</span> (<span class="hljs-keyword">double</span> x = -Radius; x &lt; radiusOuter; x += <span class="hljs-number">0.5</span>)
            {
                <span class="hljs-keyword">double</span> <span class="hljs-keyword">value</span> = x * x + y * y;

                <span class="hljs-keyword">if</span> (<span class="hljs-keyword">value</span> &gt;= radiusInner * radiusInner)
                {
                    Console.Write(OuterSymbol);
                    System.Threading.Thread.Sleep(<span class="hljs-number">50</span>);
                }
                <span class="hljs-keyword">else</span>
                {
                    Console.Write(InnerSymbol);
                }
            }
            Console.WriteLine();
        }
    }
}
</code></pre>
<p>Note that as demonstrated in the example above (in figure 63), the <code>new</code> keyword does not need to be used when instantiating an object from a struct in C#.</p>
<p>A struct is a data structure in C# that is ideal for storing a small amount of values, for example that are needed for objects derived from the <code>CircleInSquare</code> struct.</p>
<p>As discussed above, structs are value types in C# which means they are handled more efficiently in memory, where the relevant data is stored in memory on the stack. If you needed to store a sufficiently large number of instances of objects derived from the <code>CircleInSquare</code> struct in a collection, this is where a performance advantage could be noticeably gained over a scenario where object instances derived from a class version of the <code>CircleInSquare</code> template are stored within a collection.</p>
<p>So for example in a game where perhaps vector information needs to be stored in a large collection to represent the position of a <code>player</code> object, you could use a struct to represent the data rather than a class. This would help the data be managed more efficiently in memory, which brings a performance advantage as well in terms of code execution.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/NVKGxzuBe8c" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-enums-and-switch-statements">Enums and Switch Statements</h2>
<h3 id="heading-introduction-to-enums">Introduction to Enums</h3>
<p>In C#, an enum, short for enumeration, is a value type that you can use to define a set of named integral constants. Enums are used to create human readable names for a set of related and unique values, making the code more readable.</p>
<h3 id="heading-use-an-enum-in-code">Use an Enum in Code</h3>
<p>To declare an enum, you use the <code>enum</code> C# keyword. In figure 64 is a code example demonstrating the use of an enum. You can see that months of the year are represented by an enum named <code>MonthOfYear</code>. Each of the twelve members of the <code>MonthOfYear</code> enum represents a unique month of the year. Each month’s associated integer value is ordered in ascending order by the chronological order in which they occur for a calendar year.</p>
<p>So <code>Jan</code> is given the value of <code>1</code>, <code>Feb</code> is given the value of <code>2</code>,  <code>Mar</code> is given the value of <code>3</code> and so on, until the last month <code>Dec</code>, which is given a value of <code>12</code> (the twelfth and final month of the calendar year).</p>
<p>A simple method named <code>OutputMonthMainFocus</code> is passed an enum value in order to output an appropriate narrative to the user that displays the user focus for the passed-in month argument.</p>
<p>Figure 64.</p>
<pre><code class="lang-csharp">OutputMonthMainFocus(<span class="hljs-string">"Focus for Jan:"</span>, MonthOfYear.Jan);
OutputMonthMainFocus(<span class="hljs-string">"Focus for Mar:"</span>, MonthOfYear.Mar);
OutputMonthMainFocus(<span class="hljs-string">"Focus for Dec:"</span>, MonthOfYear.Dec);

<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// Focus.for Jan: Health and fitness</span>
<span class="hljs-comment">// Focus.for Mar: Increase knowledge of calculus</span>
<span class="hljs-comment">// Focus for Dec: Spend more time with friends and family</span>
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">OutputMonthMainFocus</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> prependedText, MonthOfYear month</span>)</span>
{
    <span class="hljs-keyword">switch</span> (month)
    {
        <span class="hljs-keyword">case</span> MonthOfYear.Jan:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Health and fitness"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> MonthOfYear.Feb:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Learn Spanish"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> MonthOfYear.Mar:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Increase knowledge of calculus"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> MonthOfYear.Apr:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Getting up earlier"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> MonthOfYear.May:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Better work organisation"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> MonthOfYear.Jun:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Volunteer work"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> MonthOfYear.Jul:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Eating more vegetables"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> MonthOfYear.Aug:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Travel to London"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> MonthOfYear.Sep:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Learning to cook better"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> MonthOfYear.Oct:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Learn to. surf"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> MonthOfYear.Nov:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Be more productive"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> MonthOfYear.Dec:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Spend more time with friends and family"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">default</span>:
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> ArgumentException(<span class="hljs-string">"Invalid Month"</span>);
    }
}
</code></pre>
<h3 id="heading-using-a-switch-statement-in-code-with-an-enum">Using a switch Statement in Code with an enum</h3>
<p>You can see that the above <code>switch</code> statement depicted in figure 64 is similar to an <code>if/else</code> statement.</p>
<p>At the top of the <code>switch</code> statement is code that contains the <code>switch</code> keyword. Within the brackets following the <code>switch</code> keyword is the value that the <code>switch</code> operation compares to a series of values that are denoted by each <code>case</code> statement that's encapsulated within the <code>switch</code> code block.</p>
<p>Each <code>case</code> section is comparing the value within the brackets following the <code>switch</code> keyword to a value following each <code>case</code> keyword. When a match between the value within the brackets following the <code>switch</code> keyword and a value following one of the <code>case</code> keywords is found, the statement list within the matched case section is executed.</p>
<p>For example, where the first line in the calling code (that is code that calls the <code>OutputMonthMainFocus</code> method) is called, the statement in the first case section is executed. This is because <code>Month.Jan</code> is passed in as an argument to the <code>OutputMonthMainFocus</code> method and <code>Month.Jan</code> is a match against the value following the <code>case</code> keyword in the first <code>case</code> section.</p>
<p>Note that a <code>break</code> keyword or a <code>return</code> keyword (if appropriate) must be included as the bottom statement of each case section’s statement list.</p>
<p>Each case section is mutually exclusive. This means that in the code example depicted in figure 64 where a <code>break</code> keyword is included as the bottom statement in each <code>case</code> section, when a match occurs, only the statements within that matching <code>case</code> section are run. Once the statements within that <code>case</code> statement are run, the code breaks out of the <code>switch</code> code block. If there is any code below the <code>switch</code> code block, then that code will subsequently be run. No other code within that <code>switch</code> statement will be run after a match occurs.</p>
<p>If no matches are found within any of the <code>case</code> statements, the code within the <code>default</code> section is run.</p>
<p>You can see in the example in figure 64 that the code throws an <code>ArgumentException</code> if no values within the relevant <code>case</code> statements match the value passed into the <code>switch</code> statement.</p>
<h3 id="heading-associating-one-code-block-with-more-than-one-case">Associating One Code Block with More than One Case</h3>
<p>You could alter the <code>switch</code> statement as depicted in figure 65, so that more than one case statement is associated with a block of code (or lines of code). So if, for example, <code>Month.Jan</code> was passed into the <code>switch</code> statement, the code statements within the <code>Month.Mar</code> case section would run.</p>
<p>The same lines of code within the <code>Month.Mar</code> case section would also run where <code>Month.Feb</code> or <code>Month.Mar</code> are passed in as arguments to the <code>switch</code> statement. This happens because there are no lines of coded included within the <code>Month.Jan</code> case section and there are no lines of code included within the <code>Month.Feb</code> section. So if the <code>Month.Jan</code> or <code>Month.Feb</code> sections aren't matched, the code falls through to the <code>Month.Mar</code> case section and the lines of code within the <code>Month.Mar</code> case section are run.</p>
<p>Of course the lines of code within the <code>Month.Mar</code> section will also run if the <code>Month.Mar</code> case section is matched. So the logic for this is the same as the <code>if</code> statement depicted in figure 64b.</p>
<p>Figure 64b.</p>
<pre><code class="lang-csharp">MonthOfYear month = MonthOfYear.Feb;
<span class="hljs-keyword">string</span> prependedText = <span class="hljs-string">"Focus for Feb"</span>;
<span class="hljs-keyword">if</span> (month == MonthOfYear.Jan || month == MonthOfYear.Feb || month == MonthOfYear.Mar)
{
    Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Health and fitness"</span>);
    Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Learn Spanish"</span>);
    Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Increase knowledge of calculus"</span>);
}
</code></pre>
<p>Figure 65.</p>
<pre><code class="lang-csharp">OutputMonthMainFocus(<span class="hljs-string">"Focus for Jan:"</span>, MonthOfYear.Jan);
OutputMonthMainFocus(<span class="hljs-string">"Focus for Mar:"</span>, MonthOfYear.Feb);
OutputMonthMainFocus(<span class="hljs-string">"Focus for Dec:"</span>, MonthOfYear.Mar);

<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// Focus for Jan: Health and fitness</span>
<span class="hljs-comment">// Focus for Jan: Learn Spanish</span>
<span class="hljs-comment">// Focus for Jan: Increase knowledge of calculus</span>
<span class="hljs-comment">// Focus for Mar: Health and fitness</span>
<span class="hljs-comment">// Focus for Mar: Learn Spanish</span>
<span class="hljs-comment">// Focus for Mar: Increase knowledge of calculus</span>
<span class="hljs-comment">// Focus for Dec: Health and fitness</span>
<span class="hljs-comment">// Focus for Dec: Learn Spanish</span>
<span class="hljs-comment">// Focus for Dec: Increase knowledge of calculus</span>
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">OutputMonthMainFocus</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> prependedText, MonthOfYear month</span>)</span>
{
    <span class="hljs-keyword">switch</span> (month)
    {
        <span class="hljs-keyword">case</span> MonthOfYear.Jan:
        <span class="hljs-keyword">case</span> MonthOfYear.Feb:
        <span class="hljs-keyword">case</span> MonthOfYear.Mar:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Health and fitness"</span>);
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Learn Spanish"</span>);
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Increase knowledge of calculus"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> MonthOfYear.Apr:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Getting up earlier"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> MonthOfYear.May:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Better work organisation"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> MonthOfYear.Jun:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Volunteer work"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> MonthOfYear.Jul:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Eating more vegetables"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> MonthOfYear.Aug:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Travel to London"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> MonthOfYear.Sep:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Learning to cook better"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> MonthOfYear.Oct:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Learn to. surf"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> MonthOfYear.Nov:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Be more productive"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">case</span> MonthOfYear.Dec:
            Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{prependedText}</span> Spend more time with friends and family"</span>);
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">default</span>:
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> ArgumentException(<span class="hljs-string">"Invalid Month"</span>);
    }
}
</code></pre>
<h3 id="heading-using-strings-in-switch-statements">Using Strings in switch Statements</h3>
<p>The example depicted in figure 64, specifically deals with the value list within an enum type. You can also, of course, use a <code>switch</code> statement to evaluate the values for any C# data type.</p>
<p>For example, in figure 66, values of the string data type are evaluated instead of the numeric values contained within an enum. figure 66.</p>
<pre><code class="lang-csharp">OutputMonthMainFocus(<span class="hljs-string">"Focus for Jan:"</span>, <span class="hljs-string">"JAN"</span>);
OutputMonthMainFocus(<span class="hljs-string">"Focus for Mar:"</span>, <span class="hljs-string">"MAR"</span>);
OutputMonthMainFocus(<span class="hljs-string">"Focus for Dec:"</span>, <span class="hljs-string">"DEC"</span>);
<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// Focus for Jan: Health and fitness</span>
<span class="hljs-comment">// Focus for Mar: Increase knowledge of calculus</span>
<span class="hljs-comment">// Focus for Dec: Spend more time with friends and family</span>
</code></pre>
<p>Note that you can use <code>if/else if/else</code> conditional logic where appropiate in order to replace a <code>switch</code> statement, however it is better to use a <code>switch</code> statement when there are a large number of logical conditions to evaluate. This is because a <code>switch</code> statement is more readible in this scenario.</p>
<p>You can watch the YouTube videos below to learn more about switch statements and enums.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/XTDEYQUymt8" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/1248C0V_yHs" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-inheritance-in-c">Inheritance in C</h2>
<p>C# is an object-oriented programming language. The principles of object-oriented programming are encapsulation, inheritance, polymorphism, and abstraction.</p>
<p>Inheritance is where one class is based on another class. It is important to note that multiple inheritance is not permitted in C#. A class in C# can inherit from multiple interfaces but not multiple classes at one time. We'll discuss interfaces in the next section of this handbook along with the principle of abstraction.</p>
<p>So if, for example, the <code>ManagingDirector</code> class is based on the <code>Manger</code> class, which in turn is based on the <code>Employee</code> class, in C# you cannot implement the code like in the example below (in figure 67) in order to express this inheritance hierarchy.</p>
<p>Figure 67.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">ManagingDirector</span> : <span class="hljs-title">Manager</span>, <span class="hljs-title">Employee</span>
{
    <span class="hljs-comment">// code goes here</span>
}
</code></pre>
<p>In C++, this type of multiple inheritance is permitted. But in C#, only single inheritance is permitted.</p>
<p>In C# you are, however, still able to express that the <code>ManagingDirector</code> class inherits from the <code>Manager</code> class that in turn inherits from the <code>Employee</code> class – but you have to do this in a specific way.</p>
<p>The example below (in figure 68) depicts how this specific inheritance hierarchy can be expressed in C#.</p>
<p>Figure 68.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Manager</span>:<span class="hljs-title">Employee</span>
{
    <span class="hljs-comment">// code goes here</span>
} 
<span class="hljs-keyword">public</span> ManagingDirector:Manager
{    
    <span class="hljs-comment">// code goes here</span>
}
</code></pre>
<p>So C# only supports single inheritance for classes, but you can achieve multiple inheritance by implementing code in a certain way in C#. The example above (in figure 68) shows you how to do this.</p>
<h2 id="heading-abstraction-in-c">Abstraction in C</h2>
<p>Abstraction is another principle of object-oriented programming. It is a concept that is often confused with another one of the principles of object-oriented programming, namely, encapsulation.</p>
<p>Abstraction can be defined as the inclusion of essential design related code but no implementation detail. The implementation detail is denoted by the lines of code within a method, and the abstraction of that method is the method’s method signature.</p>
<p>In the simplified example below (in figure 69), you can see a method named <code>LogData</code> that is responsible for either printing data to the console screen or printing data to a predefined local file.</p>
<p>Figure 69</p>
<pre><code class="lang-csharp"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">LogData</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> data</span>)</span>
{
    LogToScreen(data);
}
</code></pre>
<p>The abstraction of this method would be the method signature that could be represented inside an interface like in the example below depicted in figure 70:</p>
<p>Figure 70.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">ILogging</span>
{
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">LogData</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> data</span>)</span>;
}
</code></pre>
<p>The <code>LogData</code> method could reside inside a class named <code>Logging</code> that implements the <code>ILogging</code> interface. When a class implements an interface in C# this means that the class must contain and implement all the methods that are defined within the relevant <code>interface</code>.</p>
<p>See below (in figure 71) an example of the <code>Logging</code> class implementing the <code>ILogging</code> interface.</p>
<p>Figure 71</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Logging</span> : <span class="hljs-title">ILogging</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">LogData</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> data</span>)</span>
    {
        LogToScreen(data);
    }
}
</code></pre>
<p>The <code>ILogging</code> interface can be described as an abstraction of the <code>Logging</code> class. In C#, the calling code does not need to know (as it were) about the the code implementation of the <code>LogData</code> method. The calling code only needs to know about the type definition. The type definition is the abstraction of the <code>Logging</code> class.</p>
<p>In the example below (in figure 72) you can see an example of calling code instantiating an object from the <code>Logging</code> user defined type. Notice how the type definition can be implemented using the <code>ILogging</code> interface. This means the calling code will know about the <code>LogData</code> method at compile time, but will not know anything about its implementation.</p>
<p>Figure 72.</p>
<pre><code class="lang-csharp">ILogging logging = <span class="hljs-keyword">new</span> Logging();
logging.LogData(<span class="hljs-string">"Data to be logged."</span>);
</code></pre>
<p>Now you could create many logging classes with different implementations of the <code>LogData</code> method.</p>
<p>For example, currently the <code>Logging</code> class contains an implementation of the <code>LogData</code> method that logs data to the console screen. Let’s say a requirement emerges where you want to log the data to the a predefined file. To do this you could simply create a new class that implements the <code>ILogging</code> interface, where the code within the new class contains code that logs the relevant data to a predefined file.</p>
<p>The example below (in figure 73) depicts the new class. For the sake of simplicity let’s name this class <code>Logging2</code>.</p>
<p>Figure 73.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Logging2</span> : <span class="hljs-title">ILogging</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">LogData</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> data</span>)</span>
    {
        LogToFile(data);
    }
}
<span class="hljs-comment">// Calling code</span>
ILogging logging = <span class="hljs-keyword">new</span> Logging2();
logging.LogData(<span class="hljs-string">"Data to be logged."</span>);
</code></pre>
<p>The calling code that implements the <code>LogData</code> method in the <code>Logging</code> class would look very similar to when the <code>LogData</code> method is called on an object instantiated from the <code>Logging2</code> class.</p>
<p>In fact you could abstract the instantiation of the relevant <code>logging</code> object into its own factory class like you see below in figure 74. So through the use of an interface we are able to further abstract our code, by abstracting the instantiation process of the logging classes.</p>
<p>Figure 74.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">class</span> <span class="hljs-title">LoggingFactory</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> ILogging <span class="hljs-title">GetLoggingObject</span>(<span class="hljs-params"><span class="hljs-keyword">bool</span> toScreen</span>)</span>
    {
        <span class="hljs-keyword">if</span> (toScreen)
        {
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Logging();
        }
        <span class="hljs-keyword">else</span>
        {
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Logging2();
        }
    }
}
</code></pre>
<p>The calling code could now be implemented as is depicted below in figure 75.</p>
<p>Figure 75.</p>
<pre><code class="lang-csharp">ILogging logging = LoggingFactory.GetLoggingObject(<span class="hljs-literal">true</span>);
logging.LogData(<span class="hljs-string">"Log data to screen"</span>);
</code></pre>
<p>And the calling code could be implemented as is depicted in figure 76 for logging data to a predefined file.</p>
<p>Figure 76.</p>
<pre><code class="lang-csharp">ILogging logging = LoggingFactory.GetLoggingObject(<span class="hljs-literal">false</span>);
logging.LogData(<span class="hljs-string">"Log data to file"</span>);
</code></pre>
<p>We have abstracted away the implementation for both the <code>LogData</code> method as well as the instantiation of the <code>logging</code> object. This is a very basic example of how the principle of abstraction can be implemented using C# in order to create a separation of concerns.</p>
<p>You can of course create many layers of abstraction using similar techniques and various design patterns. Some key driving forces behind how you abstract your code should be better code reuse, better code readability, easier maintenance of code, design extensibility, and to facilitate better unit testing.</p>
<p>In this book, I haven't delved deep into object-oriented principles. For a more detailed explanation of object-oriented programming using C#, you can check out the videos in the playlist link below. In the videos in this playlist the object-orientied principles of encapsulation, inheritance, polymorphism and abstraction are explained and many practicle code eamples are included.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/HcjOcwMS43w" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>For a full video series on object-oriented programming in C#, please visit here:</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=HcjOcwMS43w&amp;list=PL4LFuHwItvKYD0e60jNOtT6mFKqFMH1u_">Full Video Series on Object-oriented Programming using C#</a></p>
<h2 id="heading-c-exception-handling">C# Exception Handling</h2>
<p>One of your core design criterion when designing an application should be ensuring that your application is as robust as possible.</p>
<p>In order to do this, you'll need to devise and implement a well-designed exception handling strategy. C# makes this fairly easy through the use of <code>try/catch/finally</code> blocks.</p>
<p>Exception handling is used to prevent an application from crashing. As a good rule, you should try as much as possible to prevent exceptions from being thrown through code, and only use built-in C# <code>try/catch</code> blocks to handle exceptions under truly exceptional circumstances.</p>
<p>A<code>try/catch'</code> block allows you to wrap certain code that you know, under certain exceptional circumstances, can result in your application crashing. By understanding the relevant exceptional circumstances that may cause your application to crash, you can implement the appropriate exception handling functionality.</p>
<p>You can catch specific exceptions through the <code>catch</code> section of the <code>try/catch</code> block. Then you can handle the exception appropriately either by handing the exception within the relevant catch block or by throwing the exception up the stack to be handled appropriately at a further point further up the execution stack.</p>
<p>In this very basic calculator application code example (depicted in figure 77), a method named <code>Calculate</code> is implemented to carry out the calculations.</p>
<p>Figure 77.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">try</span>
{
    <span class="hljs-keyword">int</span> result1 = Calculate(<span class="hljs-number">200000</span>, <span class="hljs-number">500000</span>, <span class="hljs-string">'*'</span>); <span class="hljs-comment">// OverFlowException occures</span>
    <span class="hljs-keyword">int</span> result2 = Calculate(<span class="hljs-number">5</span>, <span class="hljs-number">2</span>, <span class="hljs-string">'^'</span>); <span class="hljs-comment">// InvalidOperation exception will occur within the Calculate method</span>
    <span class="hljs-keyword">int</span> result3 = Calculate(<span class="hljs-number">4</span>, <span class="hljs-number">0</span>, <span class="hljs-string">'/'</span>); <span class="hljs-comment">// Attempted to divide by zero</span>
    Console.WriteLine(result1);
}
<span class="hljs-keyword">catch</span> (ArgumentException)
{
    WriteToScreen(<span class="hljs-string">"The operation symbol input is not recognised by this application"</span>);
}
<span class="hljs-keyword">catch</span> (Exception ex)
{
    WriteToScreen(ex.Message);
}
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">Calculate</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> operand1, <span class="hljs-keyword">int</span> operand2, <span class="hljs-keyword">char</span> operatorSymbol</span>)</span>
{
    <span class="hljs-keyword">int</span> result = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">try</span>
    {
        <span class="hljs-keyword">switch</span> (operatorSymbol)
        {
            <span class="hljs-keyword">case</span> <span class="hljs-string">'+'</span>:
                result = operand1 + operand2;
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-string">'-'</span>:
                result = operand1 - operand2;
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-string">'*'</span>:
                <span class="hljs-keyword">checked</span>
                {
                    result = operand1 * operand2;
                }
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-string">'/'</span>:
                result = operand1 / operand2;
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">default</span>:
                <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> InvalidOperationException();
        }
    }
    <span class="hljs-keyword">catch</span> (OverflowException)
    {
        WriteToScreen(
            <span class="hljs-string">"The result of the calculation exceeded that max value for the int data type"</span>
        );
    }
    <span class="hljs-keyword">catch</span> (InvalidOperationException ex)
    {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> ArgumentException(
            <span class="hljs-string">$"<span class="hljs-subst">{<span class="hljs-keyword">nameof</span>(operatorSymbol)}</span> is invalid"</span>,
            <span class="hljs-keyword">nameof</span>(operatorSymbol),
            ex
        );
    }
    <span class="hljs-keyword">return</span> result;
}
</code></pre>
<p>With the first call to the <code>Calculate</code> method in the above example, the calculation will yield a result that is too large to be supported by the integer data type. This means that an <code>OverFlowException</code> will be initially flagged by the C# compiler.</p>
<p>Within the <code>OverFlowException</code> catch filter in the code example depicted in figure 77, code is implemented that handles the exception locally within the <code>Calculate</code> method. This means the exception is not thrown up the stack to be handled within the calling method. The exception handling code in the <code>OverFlowException</code> catch block is simply logging a message to a file through a custom <code>LogException</code> method.</p>
<p>With the second call to the <code>Calculate</code> method, an invalid operator (that is <code>^</code>) is passed to the <code>Calculate</code> method. In the default part of the relevant <code>switch</code> statement, the code is throwing an <code>InvalidOperation</code> exception which is an exception type that is built into the C# language. Within the <code>try/catch</code> block is a <code>catch</code> filter for specifically catching this <code>InvalidOperation</code> exception.</p>
<p>Within the <code>catch</code> block, the code is throwing a new <code>ArgumentException</code> exception which is subsequently being handled within the calling method (which in this case is the <code>Main</code> method, the entry point of this application). In the relevant code example top-level-statements are enabled which means the <code>Main</code> is not present in the code but as discussed earlier, the <code>Main</code> method is added behind the scenes and encapsulates the calling code which is expressed in this example as top-level-statements.</p>
<p>The <code>Main</code> method contains an <code>ArgumentException</code> catch section. In this <code>catch</code> section, the exception is being handled by outputting an informative message to the user.</p>
<p>Arguably this type of exception would be best handled in code rather than using <code>try/catch</code> code for this purpose. You could, for example, validate the operator before the <code>Calculate</code> method is called. If the operator is entered by the user incorrectly, output an informative message to them. The user can then alter their input appropriately.</p>
<p>So in order to use validation rather than <code>try/catch</code> code in this scenario, the calling code could be changed to what you see in the example below in figure 78:</p>
<p>Figure 78.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">int</span> result = <span class="hljs-number">0</span>;
Console.WriteLine(<span class="hljs-string">"Please enter a whole number value for the first operand"</span>);
<span class="hljs-keyword">int</span> operand1 = <span class="hljs-keyword">int</span>.Parse(Console.ReadLine());
Console.WriteLine(<span class="hljs-string">"Please enter a whole number value for the second operand"</span>);
<span class="hljs-keyword">int</span> operand2 = <span class="hljs-keyword">int</span>.Parse(Console.ReadLine());
Console.WriteLine(<span class="hljs-string">"Please enter a valid operator symbol ('+','-','*','/')"</span>);
<span class="hljs-keyword">char</span> operatorSymbol = <span class="hljs-keyword">char</span>.Parse(Console.ReadLine());

<span class="hljs-keyword">if</span> (
    operatorSymbol != <span class="hljs-string">'+'</span>
    || operatorSymbol != <span class="hljs-string">'-'</span>
    || operatorSymbol != <span class="hljs-string">'*'</span>
    || operatorSymbol != <span class="hljs-string">'/'</span>
)
{
    WriteToScreen(
        <span class="hljs-string">"Incorrect operator input. The operator symbol must be one of the following ('+'’','-','*','/') "</span>
    );
}
<span class="hljs-keyword">else</span>
{
    result = Calculate(operand1, operand2, operatorSymbol);
    WriteToScreen(result.ToString());
}

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">Calculate</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> operand1, <span class="hljs-keyword">int</span> operand2, <span class="hljs-keyword">char</span> operatorSymbol</span>)</span>
{
    <span class="hljs-keyword">int</span> result = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">try</span>
    {
        <span class="hljs-keyword">switch</span> (operatorSymbol)
        {
            <span class="hljs-keyword">case</span> <span class="hljs-string">'+'</span>:
                result = operand1 + operand2;
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-string">'-'</span>:
                result = operand1 - operand2;
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-string">'*'</span>:
                <span class="hljs-keyword">checked</span>
                {
                    result = operand1 * operand2;
                }
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-string">'/'</span>:
                result = operand1 / operand2;
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">default</span>:
                <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> InvalidOperationException();
        }
    }
    <span class="hljs-keyword">catch</span> (OverflowException)
    {
        WriteToScreen(
            <span class="hljs-string">"The result of the calculation exceeded that max value for the int data type"</span>
        );
    }
    <span class="hljs-keyword">catch</span> (InvalidOperationException ex)
    {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> ArgumentException(
            <span class="hljs-string">$"<span class="hljs-subst">{<span class="hljs-keyword">nameof</span>(operatorSymbol)}</span> is invalid"</span>,
            <span class="hljs-keyword">nameof</span>(operatorSymbol),
            ex
        );
    }
}
<span class="hljs-keyword">return</span> result;
</code></pre>
<p>In this case, it's unnecessary to use exception handling, and instead you can use conditional code to validate the operator symbol before the <code>Calculate</code> method is even called.</p>
<p>It is important to note that all <code>Exception</code> types – including the ones that have been used in these code examples – are derived from the <code>Exception</code> type.</p>
<p>The <code>Exception</code> type is built into C#. All <code>Exception</code> types in C# are derived from the base <code>Exception</code> type. An exception inheritance hierarchy has been deliberately designed and implemented in C#. The exceptions I've used in the examples in this section of the book are <code>OverflowException</code>, <code>InvalidOperationException</code> and <code>ArgumentException</code>. These exception types are derived from the base <code>Exception</code> type.</p>
<p>The exception type hierarchy in C# means that when there are multiple exception filters within a <code>try/catch</code> block, the more derived exception types must be included first within the relevant list of catch filters.</p>
<p>For example, in the examples depicted in this section, the <code>ArgumentException</code> appears before the <code>Exception</code> catch filter. If the <code>Exception</code> catch filter appeared before the <code>ArgumentException</code> filter, this would mean that the code within the <code>ArgumentException</code> catch filter would never be called. So it's important that the <code>Exception</code> catch filter appear after the <code>ArgumentException</code> catch filter.</p>
<p>Note that in many cases you'll want to include a <code>finally</code> section in your <code>try/catch</code> code. This <code>finally</code> section is always called when the relevant <code>try/catch</code> code is executed. So the code included in the <code>finally</code> section is run when code within the <code>try</code> section causes an exception to occur (resulting in code within the relevant catch filter being executed) or even if no exceptions occur due to code included within the relevant <code>try</code> section. This makes the <code>finally</code>  section ideal for including clean up code, that is used for cleaning up resources (for example database connection objects) that are no longer needed.</p>
<p>For more detail on exception handling in C#, you can check out the videos in the playlist below.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/mpdg6SAaoZ4" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>For a full video series on exception handling in C#, go here:</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=mpdg6SAaoZ4&amp;list=PL4LFuHwItvKaHOvj1B5DhTnH0MJ1JFJzr">Full Video Series on Exception Handling in C#</a></p>
<p>For a full video series on file handling in C#, go here:</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=DHgU_tAC85U&amp;list=PL4LFuHwItvKaqc6w0awyyNGfkzU4ke5fu">Full Video Series on File Handling in C#</a></p>
<h2 id="heading-c-delegates">C# Delegates</h2>
<p>Delegates can be described as type safe function pointers. With a delegate, you can define a method definition that includes a parameter list as well as a return type (if no return type is included in the delegate definition, the <code>void</code> keyword must be included in place of a data type).</p>
<p>Methods that conform (appropriately in terms of their method signatures) to that defined delegate type can be referenced by the compatible delegate type. A variable can be assigned the relevant delegate and you can then use the variable to invoke any appropriate method that is referenced by the delegate.</p>
<p>In the code example depicted in figure 79 below, a delegate is defined and named <code>LogDel</code>. With the declaration of the <code>LogDel</code> delegate, a method definition for a method is declared. The method definition in this case represents any method that accepts a string argument and does not return a value (which is denoted by the <code>void</code> keyword).</p>
<p>The C# <code>void</code> keyword is used in the delegate definition to signify that any method referenced by this delegate must not return a value. Of course you can declare a delegate for a method that does return a value (in which case the delegate definition would include the appropriate data type instead of the <code>void</code> keyword).</p>
<p>In this case, however, a delegate is defined to provide an abstraction for a method that accepts a string argument and does not return a value.</p>
<p>In the code example depicted in figure 79, you can see how a delegate is used to create flexibility where calling code can reuse the <code>LogDel</code> delegate to log text to the console screen or log the text to a text file. Using this delegate definition the calling code can even implement what is known as a multi-cast delegate.</p>
<p>In this case, an instantiation of the <code>LogDel</code> delegate type is used to combine the functionality of a method that logs text to the screen as well as a method that logs text to a file. In the code, the <code>+</code> operator is used in between two delegates and the result is assigned to a delegate named <code>multiLogDel</code>.</p>
<p>When the <code>multiLogDel</code> delegate is invoked, the text is logged both to the console screen as well as to the text file. So delegates can be used to call multiple methods (that are appropriately defined where the method definitions match the delegate definition) through one invocation of the delegate instantiation.</p>
<p>Also, through the delegate, you can invoke functionality for just one of the methods – in this example either <code>LogTextToScreen</code> or <code>LogTextToFile</code>.</p>
<p>So delegates provide a type safe, flexible abstraction over methods that you can use to call one or multiple methods that conform to a specified method definition.</p>
<p>Figure 79.</p>
<pre><code class="lang-csharp">Log log = <span class="hljs-keyword">new</span> Log();
LogDel LogTextToScreenDel,
    LogTextToFileDel;
LogTextToScreenDel = <span class="hljs-keyword">new</span> LogDel(log.LogTextToScreen);
LogTextToFileDel = <span class="hljs-keyword">new</span> LogDel(log.LogTextToFile);
LogDel multiLogDel = LogTextToScreenDel + LogTextToFileDel;
Console.WriteLine(<span class="hljs-string">"Please enter your name"</span>);
<span class="hljs-keyword">var</span> name = Console.ReadLine();
LogText(multiLogDel, name);
Console.ReadKey();
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">LogText</span>(<span class="hljs-params">LogDel logDel, <span class="hljs-keyword">string</span> text</span>)</span>
{
    logDel(text);
}
<span class="hljs-function"><span class="hljs-keyword">delegate</span> <span class="hljs-keyword">void</span> <span class="hljs-title">LogDel</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> text</span>)</span>;

<span class="hljs-keyword">class</span> <span class="hljs-title">Log</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">LogTextToScreen</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> text</span>)</span>
    {
        Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{DateTime.Now}</span>: <span class="hljs-subst">{text}</span>"</span>);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">LogTextToFile</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> text</span>)</span>
    {
        <span class="hljs-keyword">using</span> (
            StreamWriter sw = <span class="hljs-keyword">new</span> StreamWriter(
                Path.Combine(AppDomain.CurrentDomain.BaseDirectory, <span class="hljs-string">"Log.txt"</span>),
                <span class="hljs-literal">true</span>
            )
        )
        {
            sw.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{DateTime.Now}</span>: <span class="hljs-subst">{text}</span>"</span>);
        }
    }
}
</code></pre>
<p>For more detail on delegates, you can watch the videos in the playlist below.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/5YTqMe2GC5U" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>For a full video series on delegates in C#, go here:</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=5YTqMe2GC5U&amp;list=PL4LFuHwItvKZwUnVL2KKvfYxNMVo-TQAB">Full Video Series on C# Delegates</a></p>
<h2 id="heading-c-events">C# Events</h2>
<p>Events can be used in C# to notify other classes or objects when, for example, a condition is met within the class or object in which that event resides. When the condition is met within the class or object that contains the event, the event can be raised. This means that those classes or objects that have elected to receive notifications when the relevant event is raised will receive those notifications.</p>
<p>The classes or objects elect to receive these notifications by subscribing in code to the event that resides in the class or object that contains the event. The class or object that contains the event is known as the publisher, and the classes or objects that have subscribed to recieve notifications when the relevant event is raised are known as the subscribers.</p>
<p>In the example depicted in figure 80 below, the publisher is the class named <code>GuessNumberGame</code>. You can see that an event named <code>GameEvent</code> has been published within this class. In this simple example, the subscription to the <code>GameEvent</code> class is made within the entry point or <code>Main</code> method of the application (shown in this example in the top-level-statements of the application).</p>
<p>Here, this is for the sake of simplicity – but in a real-world application you may have many subscriber classes subscribing to the event within the publisher class.</p>
<p>So within the calling code, a subscription to the <code>GameEvent</code> event is made through the use of the <code>+=</code> operator. This operator is used when a subscription to an event is made in C# code.</p>
<p>On the right hand side of the <code>+=</code> operator is the name of a method that is designated to handle the event when the event is raised. So this event handling method resides within the subscriber code.</p>
<p>We used a built-in C# generic delegate to define the <code>GameEvent</code> event. This in effect defines the the method definition for the method or methods that are designated to handle the event.</p>
<p>The <code>EventHandler</code> delegate provides a definition for a method that contains two parameters. One is defined as <code>object</code>, and the other is defined as a generic type argument that is passed in as an argument to the <code>EventHandler</code> delegate at compile time within the publisher class where the event is declared.</p>
<p>So you can see in the calling code, a method named <code>EventHandlerMethod</code> is defined that contains an argument of type <code>object</code>. There's also an object defined as the data type argument passed into the type parameter for the built-in generic <code>EventHandler</code> delegate, when the <code>GameEvent</code> is declared inside the publisher class.</p>
<p>So when the relevant condition is met within the <code>OnCorrectNumberGuessed</code> method, the <code>GameEvent</code> event is raised. This, in effect, results in the <code>EventHandlerMethod</code> being executed within the calling code, or within the subscriber's code, if you like.</p>
<p>The code in figure 80 is a simple game. The user gets three chances to guess a random number between 1 and 4 (including 4), generated within the <code>GuessNumberGame</code> class.</p>
<p>If the user guesses the correct number, the <code>GameEvent</code> event is raised and the code within the <code>EventHandlerMethod</code> is run. This results in outputted text being displayed to the user, informing them that they have guessed the correct number and have therefore won the game.</p>
<p>So when the user guesses the correct number, the following text is outputted to the console screen: <code>You guessed it!! Well done! :)</code>.</p>
<p>As we discussed before, the <code>+=</code> operator is used for subscribers to subscribe to an event within the publisher class or object. This lets them receive notifications when the event is raised through code within the publisher class or object.</p>
<p>After the <code>while</code> loop code, there's a line of code where the subscriber unsubscribes from the event. This is important, as it prevents possible memory leaks from occurring.</p>
<p>To unsubscribe from the event, you can use the <code>-=</code> C# operator:</p>
<p>Figure 80.</p>
<pre><code class="lang-csharp">Console.WriteLine(<span class="hljs-string">"Guess the number of which the computer is thinking. Is it 1,2,3 or 4?"</span>);
Console.WriteLine();
<span class="hljs-keyword">int</span> counter = <span class="hljs-number">0</span>;
<span class="hljs-keyword">bool</span> gameIsWon = <span class="hljs-literal">false</span>;
GuessNumberGame guessNumberGame = <span class="hljs-keyword">new</span> GuessNumberGame();
guessNumberGame.GameEvent += EventHandlerMethod;
<span class="hljs-keyword">do</span>
{
    counter++;
    Console.WriteLine(<span class="hljs-string">"Please input your number choice"</span>);
    <span class="hljs-keyword">int</span> userGuessedNumber = Int32.Parse(Console.ReadLine());
    guessNumberGame.CompareUsersNumber(userGuessedNumber);
} <span class="hljs-keyword">while</span> (gameIsWon == <span class="hljs-literal">false</span> &amp;&amp; counter &lt; <span class="hljs-number">3</span>);
guessNumberGame.GameEvent -= EventHandlerMethod;
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">EventHandlerMethod</span>(<span class="hljs-params"><span class="hljs-keyword">object</span> sender, GuessNumberDataEventArgs args</span>)</span>
{
    Console.WriteLine(args.GuessNumberGameOutputMessage);
    gameIsWon = <span class="hljs-literal">true</span>;
}

<span class="hljs-keyword">class</span> <span class="hljs-title">GuessNumberGame</span>
{
    Random rnd = <span class="hljs-keyword">new</span> Random();
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> <span class="hljs-keyword">int</span> generatedRandomNumber = <span class="hljs-number">0</span>;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">GuessNumberGame</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-keyword">this</span>.generatedRandomNumber = rnd.Next(<span class="hljs-number">1</span>, <span class="hljs-number">5</span>);
        Console.WriteLine(<span class="hljs-string">"Computer Gen ="</span> + generatedRandomNumber);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">CompareUsersNumber</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> guessedNumber</span>)</span>
    {
        <span class="hljs-keyword">if</span> (guessedNumber == <span class="hljs-keyword">this</span>.generatedRandomNumber)
        {
            OnCorrectNumberGuessed(
                <span class="hljs-keyword">new</span> GuessNumberDataEventArgs
                {
                    GuessNumberGameOutputMessage = <span class="hljs-string">"You guessed it!! Well done! :)"</span>
                }
            );
        }
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">OnCorrectNumberGuessed</span>(<span class="hljs-params">GuessNumberDataEventArgs e</span>)</span>
    {
        EventHandler &amp; lt;
        GuessNumberDataEventArgs &amp; gt;
        handler = GameEvent;
        <span class="hljs-keyword">if</span> (handler != <span class="hljs-literal">null</span>)
        {
            handler(<span class="hljs-keyword">this</span>, e);
        }
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">event</span> EventHandler&lt;GuessNumberDataEventArgs&gt; GameEvent;

}
</code></pre>
<p>For more details on using C# Events and more code examples, you can check out the YouTube video below.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/QJJKMW3ErEw" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>For a full video series on events in C#, you can go here:</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=QJJKMW3ErEw&amp;list=PL4LFuHwItvKa3dr0NL732rnnOhcc3aEgG">Full Video Series on C# Events</a></p>
<h2 id="heading-c-generics">C# Generics</h2>
<p>Generics allow C# developers to reuse specific code (like that which exists within a method, class, or collection) in the context of multiple different C# data types.</p>
<p>You determine this data type context at compile time where, for example, you can pass a data type argument to a data type parameter that is contained within the definition of the method, class, or collection type.</p>
<p>A simple code example of this is the C# generic <code>List</code> type, which is a built-in collection you can use. You can strongly type a generic list at compile time with C# built-in data types like <code>int</code>, <code>string</code>, <code>char</code>, <code>bool</code>, <code>decimal</code>, <code>float</code>, <code>double</code> and so on, as well as user defined types, like those that are implemented using a class or a struct.</p>
<p>In the example depicted in figure 82, the generic list type is being used to store the grades of a university student. All of the grades are integers. When you look at the definition for the <code>List</code> generic type that is built into C#, you see the word <code>List</code> followed by angle brackets, with a <code>T</code> included within the angle brackets. So the generic built-in C# <code>List</code> type is defined as is depicted in figure 81.</p>
<p>The <code>T</code> is a placeholder representing the generic data type parameter, which you can use to pass a data type argument to the 'List' type at compile time in order to strongly type the list.</p>
<p>Generics means that type parameters are included in .NET. This makes it possible for you to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by calling code.</p>
<p>Figure 81.</p>
<pre><code class="lang-csharp">List&lt;T&gt;
</code></pre>
<p>Figure 82.</p>
<pre><code class="lang-csharp">List&lt;<span class="hljs-keyword">int</span>&gt; grades = <span class="hljs-keyword">new</span> List&lt;<span class="hljs-keyword">int</span>&gt;();
grades.Add(<span class="hljs-number">60</span>);
grades.Add(<span class="hljs-number">73</span>);
grades.Add(<span class="hljs-number">85</span>);
grades.Add(<span class="hljs-number">92</span>);
<span class="hljs-keyword">foreach</span> (<span class="hljs-keyword">int</span> grade <span class="hljs-keyword">in</span> grades)
{
    Console.Write(<span class="hljs-string">$"<span class="hljs-subst">{grade}</span>, "</span>);
}

<span class="hljs-comment">// Output: 60, 73, 85, 92,</span>
<span class="hljs-comment">// You could also use the generic list to store the subject names pertaining to the grades of the relevant</span>
<span class="hljs-comment">// student.</span>
List&lt;<span class="hljs-keyword">string</span>&gt; subjects = <span class="hljs-keyword">new</span> List&lt;<span class="hljs-keyword">string</span>&gt;();
subjects.Add(<span class="hljs-string">"Observational Astronomy"</span>);
subjects.Add(<span class="hljs-string">"Particle Physics"</span>);
subjects.Add(<span class="hljs-string">"Quantum mechanics"</span>);
subjects.Add(<span class="hljs-string">"Advanced Math"</span>);
</code></pre>
<p>You can also use the same generic list data type to store objects derived from a specific user defined type, implemented, for example, as a class in code.</p>
<p>So in the example in figure 83, the list data type is used to store a collection of 'student' objects:</p>
<p>Figure 83.</p>
<pre><code class="lang-csharp">List&lt;Student&gt; students = <span class="hljs-keyword">new</span> List&lt;Student&gt;();
students.Add(
    <span class="hljs-keyword">new</span> Student
    {
        Id = <span class="hljs-number">1</span>,
        Name = <span class="hljs-string">"Dale Jones"</span>,
        Grade = <span class="hljs-number">60</span>
    }
);
students.Add(
    <span class="hljs-keyword">new</span> Student
    {
        Id = <span class="hljs-number">2</span>,
        Name = <span class="hljs-string">"Gale Davis"</span>,
        Grade = <span class="hljs-number">89</span>
    }
);
students.Add(
    <span class="hljs-keyword">new</span> Student
    {
        Id = <span class="hljs-number">3</span>,
        Name = <span class="hljs-string">"Debbie Hill"</span>,
        Grade = <span class="hljs-number">56</span>
    }
);
students.Add(
    <span class="hljs-keyword">new</span> Student
    {
        Id = <span class="hljs-number">4</span>,
        Name = <span class="hljs-string">"Dave Brown"</span>,
        Grade = <span class="hljs-number">76</span>
    }
);
<span class="hljs-keyword">foreach</span> (Student student <span class="hljs-keyword">in</span> students)
{
    Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{student.Id}</span> <span class="hljs-subst">{student.Name}</span> <span class="hljs-subst">{student.Grade}</span> "</span>);
}
<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// 1 Dale Jones 60</span>
<span class="hljs-comment">// 2 Gale Davis 89</span>
<span class="hljs-comment">// 3 Debbie Hill 56</span>
<span class="hljs-comment">// 4 Dave Brown 76</span>
</code></pre>
<p>Through generics, you are able to reuse the functionality in the built-in <code>list</code> data type to store multiple types of data. Any generic list used in your C# code must be strongly typed with one particular data type.</p>
<p>You can strongly type the generic list by passing in the relevant type as an argument when defining and instantiating an object of the <code>List</code> type.</p>
<p>Prior to the generic <code>List</code> type being introduced (in .NET Framework 2.0), you could use an <code>ArrayList</code> to store a collection of heterogeneous data types. You could store multiple different data types within one <code>ArrayList</code>.</p>
<p>The problem with the <code>ArrayList</code> is that any calling code retrieving an item from an <code>ArrayList</code> must first convert that value to its appropriate data type before the value can be of any use.</p>
<p>Every item stored in an <code>ArrayList</code> is ‘boxed' within the <code>object</code> type. This is possible because all C# data types inherit from the <code>object</code> data type, so every data type in C# can be implicitly boxed into an object.</p>
<p>Boxing is simply the process of converting a value type to the <code>object</code> type in C#. When the common language runtime (CLR) boxes a value type, it wraps the value inside a <code>System.Object</code> instance and stores it on the managed heap. So in order to use an item retrieved from an <code>ArrayList</code>, the object must first be converted or 'unboxed' into its original type.</p>
<p>This highlights one of the main advantages of using generics in C#. Through using the generic <code>List</code> to store strongly typed items in a collection, you can avoid 'boxing' and 'unboxing'. This means that with generics, the performance overhead caused through 'boxing' and 'unboxing' is also avoided.</p>
<p>The other main advantage is that you can avoid type-related errors that can occur as a result of explicit type conversions needing to be performed on an item retrieved from an <code>ArrayList</code> at runtime.</p>
<p>So by strongly typing a <code>List</code> at compile time, the compiler is able to check that all data type-related code is correct before it is deployed into production. In this way, data type-related errors are preempted at compile time.</p>
<p>Depicted in figure 84, is an example of using an <code>ArrayList</code>  to store heterogeneous data types.</p>
<p>Figure 84.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> System.Collections;
<span class="hljs-keyword">using</span> System.ComponentModel;

ArrayList studentDetails = <span class="hljs-keyword">new</span> ArrayList();
<span class="hljs-keyword">int</span> grade = <span class="hljs-number">90</span>;
<span class="hljs-keyword">string</span> name = <span class="hljs-string">"Bob Jones"</span>;
studentDetails.Add(<span class="hljs-number">90</span>); <span class="hljs-comment">// int value boxed as object</span>
studentDetails.Add(<span class="hljs-string">"Bob Jones"</span>);
studentDetails.Add(
    <span class="hljs-keyword">new</span> Student
    {
        Id = <span class="hljs-number">1</span>,
        Name = <span class="hljs-string">"Bob Jones"</span>,
        Grade = <span class="hljs-number">90</span>
    }
);
grade = Convert.ToInt32(studentDetails[<span class="hljs-number">0</span>]); <span class="hljs-comment">// runtime performance slowed by unboxing int student = int32.Parse(studentDetails[2]); // This would result in a runtime exception being thrown due to an invalid type conversion operation being performed at runtime</span>
</code></pre>
<p>So you can see that using a generic <code>List</code> to store strongly typed values in a collection (rather than an <code>ArrayList</code> where 'boxing' and 'unboxing' code needs to be performed) results in a performance improvement. It also ensures better robustness at runtime.</p>
<p>The example depicted in figure 85 is a more complicated example of using generics in C#. In this example, the factory pattern is employed where you can reuse the <code>GetInstance</code> method to instantiate objects of different types using the same instantiation functionality enveloped in the <code>GetInstance</code> method.</p>
<p>You can see that <code>K</code> and <code>T</code> are used as placeholders to represent the types that can be passed as arguments to the class at compile time (that is, in order to strongly type the class). The <code>where</code> keyword denotes constraints (which are defined rules) on the type arguments passed to this class.</p>
<p>So these constraints mean that the type passed as an argument to the parameter represented by the <code>T</code> placeholder must be a class. The <code>new</code> keyword followed by open and closed brackets denotes that a new object must be created from the relevant class which is of type <code>K</code>.</p>
<p>Figure 85.</p>
<pre><code class="lang-csharp"><span class="hljs-comment">// Instantiation of objects from the generic types passed as objects to the FactoryPattern class.</span>
IStudent student = FactoryPattern&lt;IStudent, Student&gt;.GetInstance();
student.Name = <span class="hljs-string">"Bob Jones"</span>;
student.Grade = <span class="hljs-number">78</span>;
student.Subject = <span class="hljs-string">"Math"</span>;
Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{student.Name}</span> <span class="hljs-subst">{student.Grade}</span> <span class="hljs-subst">{student.Subject}</span>"</span>);
IStudent student2 = FactoryPattern&lt;IStudent, Student&gt;.GetInstance();
student2.Name = <span class="hljs-string">"Debbie Long"</span>;
student2.Grade = <span class="hljs-number">84</span>;
student2.Subject = <span class="hljs-string">"Science"</span>;
Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{student2.Name}</span> <span class="hljs-subst">{student2.Grade}</span> <span class="hljs-subst">{student2.Subject}</span>"</span>);
IProfessor professor = FactoryPattern&lt;IProfessor, Proffessor&gt;.GetInstance();
professor.Name = <span class="hljs-string">"Ron Willis"</span>;
professor.MainSubject = <span class="hljs-string">"Math"</span>;
Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{professor.Name}</span> <span class="hljs-subst">{professor.MainSubject}</span>"</span>);

<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// Bob Jones 78 Math</span>
<span class="hljs-comment">// Debbie Long 84 Science</span>
<span class="hljs-comment">// Ron Willis Math</span>
<span class="hljs-keyword">static</span> <span class="hljs-keyword">class</span> <span class="hljs-title">FactoryPattern</span>&lt;<span class="hljs-title">K</span>, <span class="hljs-title">T</span>&gt;
    <span class="hljs-keyword">where</span> <span class="hljs-title">T</span> : <span class="hljs-keyword">class</span>, <span class="hljs-title">K</span>, <span class="hljs-title">new</span>()
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> K <span class="hljs-title">GetInstance</span>(<span class="hljs-params"></span>)</span>
    {
        K objK;
        objK = <span class="hljs-keyword">new</span> T();
        <span class="hljs-keyword">return</span> objK;
    }
}
</code></pre>
<p>So in the example depicted in figure 85, generics is used to create clean, reusable code for the implementation of the factory pattern.</p>
<p>A single code block is used to create instances of objects derived from multiple user defined types. Through generics the amount of code is minimised, and if you have a good knowledge of generics, this code is easy to maintain and reuse. Generics gives you greater design flexibility, and ensures better runtime performance and robustness.</p>
<p>For more information on C# Generics and more code examples, you can watch the YouTube video below.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/UUF8QCf3rpI" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>For a full video series on generics in C#, you can go here:</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=UUF8QCf3rpI&amp;list=PL4LFuHwItvKaeSVOur67Lu-0I7sfjf5N3">Full Video Series on C# Generics</a></p>
<h2 id="heading-linq">LINQ</h2>
<p>LINQ stands for Language-Integrated Query and was first introduced to .NET languages with .NET Framework version 3.5 in 2007. It provides .NET developers with a high level query abstraction where, for example, C# code can be used to natively query collections of C# objects. It's similar to the well known relational database management system declarative query language, T-SQL – but the entities being queried with LINQ code are collections of objects rather than rows within database tables.</p>
<p>The code example depicted in figure 86 shows how T-SQL might be used to query a database table named, <code>Employees</code>, in order to bring back all the field values in each row stored in the <code>Employees</code> database table.</p>
<p>Figure 86.</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> Employees
</code></pre>
<p>In figure 87, a code example is depicted where LINQ in C# code is leveraged to query a collection of <code>Employee</code> objects.</p>
<p>Figure 87</p>
<pre><code class="lang-csharp">List&lt;Employee&gt; employees = <span class="hljs-keyword">new</span> List&lt;Employee&gt;();
employees.Add(
    <span class="hljs-keyword">new</span> Employee
    {
        Id = <span class="hljs-number">1</span>,
        FirstName = <span class="hljs-string">"Gavin"</span>,
        LastName = <span class="hljs-string">"Lon"</span>,
        Salary = <span class="hljs-number">10000</span>
    }
);
employees.Add(
    <span class="hljs-keyword">new</span> Employee
    {
        Id = <span class="hljs-number">2</span>,
        FirstName = <span class="hljs-string">"Sandy"</span>,
        LastName = <span class="hljs-string">"James"</span>,
        Salary = <span class="hljs-number">90000</span>
    }
);
employees.Add(
    <span class="hljs-keyword">new</span> Employee
    {
        Id = <span class="hljs-number">3</span>,
        FirstName = <span class="hljs-string">"Greg"</span>,
        LastName = <span class="hljs-string">"Jones"</span>,
        Salary = <span class="hljs-number">73000</span>
    }
);
<span class="hljs-keyword">var</span> employeeResults = <span class="hljs-keyword">from</span> e <span class="hljs-keyword">in</span> employees <span class="hljs-keyword">select</span> e;
<span class="hljs-keyword">foreach</span> (Employee emp <span class="hljs-keyword">in</span> employees)
{
    Console.WriteLine(emp.FirstName);
}
</code></pre>
<p>If for example the <code>Employees</code> database table contained four fields, namely <code>Id</code>, <code>FirstName</code>, <code>LastName</code> and <code>Salary</code>, and you wanted to only bring back the <code>FirstName</code> and <code>LastName</code> fields through your T-SQL query, your query would look like the example in figure 88.</p>
<p>Figure 88.</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> FirstName, LastName <span class="hljs-keyword">FROM</span> Employees
</code></pre>
<p>In order to bring back the <code>FirstName</code> and <code>LastName</code> fields from a collection of objects where each object has an <code>Id</code> property, a <code>FirstName</code> property, a <code>LastName</code> property, and a <code>Salary</code> property your LINQ query could be implemented as is shown in the code example in figure 89.</p>
<p>Figure 89.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> employeeResults =
    <span class="hljs-keyword">from</span> e <span class="hljs-keyword">in</span> employees
    <span class="hljs-keyword">select</span> <span class="hljs-keyword">new</span> Employee { FirstName = e.FirstName, LastName = e.LastName };
</code></pre>
<p>There are two types of syntax you can leverage to implement LINQ in C#. The type of syntax you've seen so far in this section is known as query syntax. Another way to implement LINQ code is by using method syntax.</p>
<p>To illustrate the use of query syntax vs method syntax, let's look at a slightly more complex example. In the example depicted in figure 90, a T-SQL query is used to bring back the <code>FirstName</code> and <code>LastName</code> fields, for rows pertaining to employees that have a salary higher than <code>50000</code>.</p>
<p>Figure 90.</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> FirstName, LastName <span class="hljs-keyword">FROM</span> Employees e <span class="hljs-keyword">WHERE</span> e.Salary &gt; <span class="hljs-number">50000</span>
</code></pre>
<p>Using Query syntax in LINQ to perform the equivalent query against a collection of <code>Employee</code> objects, the code would look like what is depicted in figure 91.</p>
<p>Figure 91.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> employeeResults =
    <span class="hljs-keyword">from</span> e <span class="hljs-keyword">in</span> employees
    <span class="hljs-keyword">where</span> e.Salary &gt; <span class="hljs-number">50000</span>
    <span class="hljs-keyword">select</span> <span class="hljs-keyword">new</span> Employee
    {
        FirstName = e.FirstName,
        LastName = e.LastName,
        Salary = e.Salary
    };
</code></pre>
<p>Using method syntax in LINQ, the equivalent query could be implemented with the code depicted in figure 92.</p>
<p>Figure 92.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> employeeResults = employees
    .Select(e =&gt; <span class="hljs-keyword">new</span> Employee
    {
        FirstName = e.FirstName,
        LastName = e.LastName,
        Salary = e.Salary
    })
    .Where(e =&gt; e.Salary &gt; <span class="hljs-number">50000</span>);
</code></pre>
<p>These LINQ related code examples hopefully give you a sense of how method syntax looks compared to query syntax.</p>
<p>Note that you can't create all LINQ queries using query syntax, so depending on your requirements you may have to use method syntax for performing certain queries using LINQ.</p>
<p>Behind the scenes, the C# compiler converts query syntax to method syntax. Query syntax was introduced in the LINQ technology specifically to improve the readability of your queries.</p>
<p>LINQ is made up of many extension methods that reside within the <code>System.LINQ</code> namespace. In the example in figure 92, the <code>Select</code> and <code>Where</code> LINQ extension methods have been appropriately chained together to create the desired query.</p>
<p>For more detils on LINQ and for more code examples, you can watch the  YouTube video below.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/UfZOmSCCbDY" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>For a full video series on LINQ, you can go here:</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=UfZOmSCCbDY&amp;list=PL4LFuHwItvKbzDl6MBp3XY0MrnALSfyub">Full Video Series on Using LINQ in C#</a></p>
<h2 id="heading-c-attributes">C# Attributes</h2>
<p>You can associate metadata with program entities (for example assemblies, types, methods, and properties) through the use of attributes in C#.</p>
<p>Attributes are powerful when combined with reflection (a concept we'll discuss in the next section). Through the use of reflection, the attributes can be queried at runtime and then custom functionality can be executed based on the metadata provided through the use of the relevant attributes.</p>
<p>Attributes in C# are created as objects at runtime. Their properties and methods can be used just like any other object in C#.</p>
<p>There are two broad categories for attributes: predefined attributes and custom attributes. Predefined attributes are built into the base class libraries provided in .NET, and custom attributes allow you to define your own attributes that address your unique application requirements.</p>
<p>An example of a predefined general attribute is the <code>obsolete</code> attribute. You can check out figure 93 for a code example depicting how you can use the <code>obsolete</code> attribute and how it can be useful when you're attempting to consume an obsolete method (or a method marked as obsolete with the <code>obsolete</code> attribute).</p>
<p>In the code example, you can see that the <code>obsolete</code> attribute decorates a method named <code>LogToScreen</code>. A new updated method named <code>LogToFile</code> has been created within the same class to replace the old <code>LogToScreen</code> method. So the creator of the <code>Logging</code> class would prefer the <code>LogToFile</code> method be consumed by developers (when applying logging functionality in calling code) rather than the <code>LogToScreen</code> method.</p>
<p>When the consumer of the class tries to use the older obsolete method (in this example, the <code>LogToScreen</code> method), a predefined warning message can be displayed to the developer from inside their code editor. This warning message is created to warn developers who wish to consume the logging functionality that the <code>LogToFile</code> method should be used for logging and not the obsolete <code>LogToScreen</code> method.</p>
<p>So to ensure that an appropriate message is displayed, you can pass an appropriate custom message as an argument to the <code>obsolete</code> attribute that appropriately decorates the <code>LogToScreen</code> method (which has now been deemed as obsolete). The warning message can for example warn developers that the old method (<code>LogToScreen</code>) is now obsolete and direct them to use the new preferred method (<code>LogToFile</code>) in its place.</p>
<p>Figure 93.</p>
<pre><code class="lang-csharp">Logging logAction = <span class="hljs-keyword">new</span> Logging();
logAction.LogToScreen(<span class="hljs-string">"Start of Code"</span>); <span class="hljs-comment">// This message, "The LogToScreen method is now obsolete. Please use the LogToFile method instead" is flagged by the C# compilerSomeFunction();</span>
logAction.LogToScreen(<span class="hljs-string">"End of Code"</span>); <span class="hljs-comment">// This message, "The LogToScreen method is now obsolete. Please use the LogToFile method instead" is flagged by the C# compiler</span>
</code></pre>
<p>In the example depicted in figure 94, a custom attribute is created through the implementation of a C# class that inherits from the built-in C# class <code>System.Attribute</code>. A general predefined attribute named, <code>AttributeUsage</code> is used to decorate the class in order to enforce the usage rules associated with the <code>Required</code> custom attribute.</p>
<p>The arguments being passed (in this example) to the <code>AttributeUsage</code> attribute establish the rules where the <code>Required</code> attribute can only be associated with field, parameter, and property program elements, and cannot be applied to the same element multiple times.</p>
<p>The <code>Required</code> attribute can only be applied to a particular program element once, and can be applied to fields, parameters, and properties.</p>
<p>In the example depicted in <strong>figure 94</strong>, a very basic use of a custom attribute is implemented where an custom attribute named <code>RequiredAttribute</code> is used to decorate certain properties of a model. Note that when a custom attribute is actually applied, the 'Attribute' part of the custom attribute's name can be omitted. So in <strong>figure 94</strong> you can see that the relevant program elements are decorated with the attribute named,<code>Required</code> and not <code>RequiredAttribute</code>.</p>
<p>The <code>EmployeeModel</code> model class is used to represent an <code>Employee</code> record. The class named, <code>EmployeeModel</code>, provides a template for an employee record. The <code>Required</code> attribute gives you the ability to reuse this custom attribute across properties where <code>Required</code> validation is necessary (that is, where a user must input a value that is subsequently assigned to the property decorated with the <code>Required</code> attribute).</p>
<p>In the calling code, reflection is employed to inspect the property program elements of the <code>EmployeeModel</code> user defined type at runtime to see if there are any attributes applied to its properties.</p>
<p>In this basic example, the code queries the <code>Id</code> property of the <code>EmployeeModel</code> class, and the <code>Required</code> attribute is found to be associated with the <code>Id</code> property. The code then knows to appropriately validate the user's input for the <code>Id</code> property of the <code>EmployeeModel</code> class.</p>
<p>Note that the <code>Required</code> attribute is also applied to the <code>FirstName</code> property. So you can see how an attribute can be applied multiple times in order to address cross cutting concerns.</p>
<p>Figure 94.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> System.Reflection;

Console.WriteLine(<span class="hljs-string">"Please enter an Id for the employee:"</span>);
<span class="hljs-keyword">string</span> id = Console.ReadLine();
Type employeeType = <span class="hljs-keyword">typeof</span>(EmployeeModel);
PropertyInfo prop = employeeType.GetProperty(<span class="hljs-string">"Id"</span>);
Attribute[] attributes = prop.GetCustomAttributes().ToArray();
<span class="hljs-keyword">foreach</span> (Attribute attr <span class="hljs-keyword">in</span> attributes)
{
    <span class="hljs-keyword">if</span> (attr <span class="hljs-keyword">is</span> RequiredAttribute)
    {
        <span class="hljs-keyword">if</span> (<span class="hljs-keyword">string</span>.IsNullOrEmpty(id))
        {
            Console.WriteLine(
                <span class="hljs-string">"The employee’s Id is required. You did not enter the employee’s Id. "</span>
            );
        }
    }
}

<span class="hljs-keyword">class</span> <span class="hljs-title">EmployeeModel</span>
{
    [<span class="hljs-meta">Required</span>]
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> Id { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

    [<span class="hljs-meta">Required</span>]
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> FirstName { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> LastName { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
}

[<span class="hljs-meta">AttributeUsage(
    AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property,
    AllowMultiple = false
)</span>]
<span class="hljs-keyword">class</span> <span class="hljs-title">RequiredAttribute</span> : <span class="hljs-title">Attribute</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> ErrorMessage { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">RequiredAttribute</span>(<span class="hljs-params"></span>)</span>
    {
        ErrorMessage = <span class="hljs-string">"You cannot leave field, {0}, empty"</span>;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">RequiredAttribute</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> errorMessage</span>)</span>
    {
        ErrorMessage = errorMessage;
    }
}
</code></pre>
<p>You can check out the following video that contains more details and code examples pertaining to C# Attributes.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/JOM6zDb9Wa8" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-reflection-in-c">Reflection in C</h2>
<p>Reflection is a concept in C#, where the programmer is able to create C# code that can dynamically read the metadata of .NET assemblies at runtime. This gives you a powerful tool where you can create code to dynamically analyse a .NET assembly based on the assembly's metadata at runtime. Your code can for e.g. read the assemblies relevant metadata using Reflection, and output the descriptive metadata about the analysed assembly.</p>
<p>Reflection can even be used to dynamically bind an object to a specific type that resides within the assembly at runtime and execute code that resides within the type’s methods. This is known as late binding.</p>
<p>Most of the time, you won't use reflection to call the code within a .NET assembly and will rather use early binding. Early binding means the C# compiler knows (as it were) about the assemblies' relevant program elements for e.g. an assemblies' classes and public methods at compile time.</p>
<p>Using early binding is the safest way to consume a type’s functionality, because any potential exceptions related to calling code within the early bound object are flagged at compile time. This prevents potentially erroneous code from being released into production, where it can result in runtime errors occurring.</p>
<p>When early binding is used, due to the self-describing nature of .NET assemblies where metadata is stored within the .NET assembly, the C# compiler is able to know (as it were) all the relevant details about the assembly at compile time.</p>
<p>So this metadata stored within .NET assemblies means early binding is possible, where the C# compiler has all the necessary type knowledge, if you like, at compile time.</p>
<p>Using reflection, you are able to use the technique of late binding which occurs at runtime. Late binding can be used to dynamically bind to an object (derived from a type that resides within the relevant assembly) at runtime and consume functionality that resides within the relevant .NET assembly.</p>
<p>This is a powerful tool, but is not a safe way to execute the functionality within a .NET assembly, because late binding means that the calling code learns about the target assembly at runtime by reading its metadata before executing the code within the assembly. The technique of late binding is therefore more prone to runtime errors, as potential errors cannot be dealt with at compile time – that is, before the code within the assembly is executed at runtime.</p>
<p>In the example depicted in figure 96, code within an assembly is dynamically invoked using reflection and late binding.</p>
<p>Figure 95.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> System;
<span class="hljs-keyword">using</span> System.Collections.Generic;
<span class="hljs-keyword">using</span> System.Text;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">UtilityFunctions</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">BasicMathFunctions</span>
    {
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">double</span> <span class="hljs-title">DivideOperation</span>(<span class="hljs-params"><span class="hljs-keyword">double</span> number1, <span class="hljs-keyword">double</span> number2</span>)</span>
        {
            <span class="hljs-keyword">return</span> number1 / number2;
        }

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">double</span> <span class="hljs-title">MultiplyOperation</span>(<span class="hljs-params"><span class="hljs-keyword">double</span> number1, <span class="hljs-keyword">double</span> number2</span>)</span>
        {
            <span class="hljs-keyword">return</span> number1 * number2;
        }
    }
}
</code></pre>
<p>A code example is depicted in figure 96, where the code resides within a different assembly to the assembly that contains the <code>BasicMathFunctions</code> type depicted in figure 95.</p>
<p>In the calling code (depicted in figure 96), reflection is used to late bind to the <code>BasicMathFunctions</code> type and call the <code>MultiplyOperation</code> method. So the code depicted in figure 95 resides within an assembly denoted by a file named "UtilityFunctions.dll".</p>
<p>The "UtilityFunction.dll" assembly resides within the same directory as the assembly that contains the calling code (depicted in figure 96). Reflection is used to dynamically load the "UtilityFunctions" assembly, late bind to the <code>BasicMathFunctions</code> type, and call its <code>MultiplyOperation</code> method.</p>
<p>Figure 96.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> System.Reflection;

<span class="hljs-keyword">const</span> <span class="hljs-keyword">string</span> TargetAssemblyFileName = <span class="hljs-string">"UtilityFunctions.dll"</span>;
<span class="hljs-keyword">const</span> <span class="hljs-keyword">string</span> TargetNamespace = <span class="hljs-string">"UtilityFunctions"</span>;
Assembly assembly = Assembly.LoadFile(
    Path.Combine(AppDomain.CurrentDomain.BaseDirectory, TargetAssemblyFileName)
);
Type classType = assembly.GetType(<span class="hljs-string">"UtilityFunctions.BasicMathFunctions"</span>);
<span class="hljs-keyword">object</span> classInstance = Activator.CreateInstance(classType);
MethodInfo method = classType.GetMethod(<span class="hljs-string">"MultiplyOperation"</span>);
<span class="hljs-keyword">object</span>[] paramValues = <span class="hljs-keyword">new</span> <span class="hljs-keyword">object</span>[<span class="hljs-number">2</span>];
paramValues[<span class="hljs-number">0</span>] = <span class="hljs-number">2</span>;
paramValues[<span class="hljs-number">1</span>] = <span class="hljs-number">3</span>;
<span class="hljs-keyword">object</span> result = method.Invoke(classInstance, paramValues);
Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{paramValues[<span class="hljs-number">0</span>]}</span> * <span class="hljs-subst">{paramValues[<span class="hljs-number">1</span>]}</span>  = <span class="hljs-subst">{result}</span>"</span>);
<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// 2 * 3  = 6</span>
</code></pre>
<p>For more details and code examples pertaining to reflection, you can watch the YouTube video below.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/tGMa9qjncjs" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-video-on-asynchronous-programming-in-c">Video on Asynchronous Programming in C</h2>
<p>I haven't covered Asynchronous programming in this C# book. But if you'd like to learn about Asynchronous programming in C#, you can watch the YouTube video below.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/MyblIAk8cNI" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>For a full video series on asynchronous programming in C#, check this out:</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=MyblIAk8cNI&amp;list=PL4LFuHwItvKb5A9W1myICdC-GJU4_6cKE">Full Video Series on Asynchronous Programming in C#</a></p>
<p>If you'd like to learn about how to create sophisticated web applications using C#, I've provided some resources below.</p>
<p>The first link takes you do a YouTube video playlist that provides step by step instructions on how to build a Shopping Cart SPA (Single Page Application) using the Blazor framework. The second link takes you to a YouTube video playlist that provides step by step instructions on how to build a real-word web application using the ASP .NET Core MVC framework.</p>
<ul>
<li><a target="_blank" href="https://www.youtube.com/watch?v=3_AsedRrqww&amp;list=PL4LFuHwItvKbdK-ogNsOx2X58hHGeQm8c">Full Blazor Shopping Cart SPA (Single Page Application) Course</a></li>
<li><a target="_blank" href="https://www.youtube.com/watch?v=D7R_ToqDKHg&amp;list=PL4LFuHwItvKZ6Mz5W5wzD9uo3w6tNChhX">Full ASP .Net CORE MVC Course</a></li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The goal of this book is to help you gain an understanding of the powerful features available in the C# programming language. The code examples were designed to provide you with a practical knowledge of these features.</p>
<p>You can apply these code examples yourself using free tools like Visual Studio 2022 Community edition or Visual Studio Code in order to gain hands-on experience working with the concepts discussed in this book.</p>
<p>I have worked with C# for over two decades and have been impressed with the evolution of the language itself as well as the environment in which C# code runs, namely .NET. When you master C#, a whole world of creativity, intellectually challenging concepts, and a multitude of career opportunities will open up to you.</p>
<p>In today’s world, you have the benefit of development tools as well as instructions on how to use those development tools freely available to you. There is also a lot of free content available online on how to use the C# programming language in order to create real-world applications.</p>
<p>Using C#, you can create a large variety of different types of applications. You can create cross platform desktop applications, cross platform mobile applications, a variety of types of web applications like SPAs that leverage the Blazor framework. You can create sophisticated 2D and 3D games. You can create IoT applications. You can create globally distributed cloud native applications that leverage the Micro-service architecture.</p>
<p>You are almost unlimited in terms of the types of applications you can create for a multitude of types of platforms and devices. With C# you can easily integrate AI into your applications as well.</p>
<p>It is a very exciting time to be a C# and .NET developer. I wish you the very best with learning and leveraging this powerful programming language on your journey as a developer!</p>
<p>For a full course for C# beginners and a full Advanced C# course, check out these resources:</p>
<ul>
<li><a target="_blank" href="https://www.youtube.com/watch?v=2pquQMSYk6c&amp;list=PL4LFuHwItvKbneXxSutjeyz6i1w32K6di">Full C# for Beginners Course</a></li>
<li><a target="_blank" href="https://www.youtube.com/watch?v=3cfVmcAkR2w&amp;list=PL4LFuHwItvKaOi-bN1E2WUVyZbuRhVokL">Full Advanced C#  Course</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Device Descriptor Request Failed – How to Fix Unknown USB Device Error in Windows 10 ]]>
                </title>
                <description>
                    <![CDATA[ Recently my uncle, who lives in Australia, sent my parents, who live in South Africa, a flash drive that was full of pictures of our Australian family getting up to various Australian activities.  But it was very frustrating for my poor Mom when her ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/device-descriptor-request-failed-windows-error-solved/</link>
                <guid isPermaLink="false">66b0c58563f46c9b72e6d5d8</guid>
                
                    <category>
                        <![CDATA[ error ]]>
                    </category>
                
                    <category>
                        <![CDATA[ usb ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Windows 10 ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Gavin Lon ]]>
                </dc:creator>
                <pubDate>Fri, 28 Oct 2022 23:49:33 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/10/Screenshot1.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Recently my uncle, who lives in Australia, sent my parents, who live in South Africa, a flash drive that was full of pictures of our Australian family getting up to various Australian activities. </p>
<p>But it was very frustrating for my poor Mom when her laptop would not recognise the USB device (the flash drive containing the Australian family pictures). </p>
<p>I have the <em>privilege</em> of being the goto family member when anything goes wrong with something computer related, because I am a computer programmer. This means I must know everything about USB ports, printers, scanners, basically all things computer related….right? </p>
<p>Well, at the time, I must confess I didn’t have a clue why Windows 10 could not recognise the flash drive. So I did a bit of research. In this particular case the external device (the flash drive) was the offending party. </p>
<p>It turns out, however, that this “Device Descriptor Request Failed“ issue can occur for many different reasons, some hardware related and others software related. </p>
<p>In this article I'll cover the possible hardware-related issues first, and then we'll get into the possible software-related issues. With each cause of the “Device Descriptor Request Failed“ error, I’ll take you through the steps you'll need to follow to resolve the issue.</p>
<h2 id="heading-possible-causes-and-fixes-for-device-descriptor-request-failed-error">Possible Causes and Fixes for "Device Descriptor Request Failed" Error</h2>
<p>The following seven headings list out what may have caused the “Device Descriptor Request Failed“ issue. In the subsequent sections of this article, I'll give you details on how you might be able to resolve the issue.</p>
<ul>
<li><strong>USB Hardware Fault</strong></li>
<li><strong>Run Hardware and Device Troubleshooter</strong></li>
<li><strong>Update USB Device Driver</strong></li>
<li><strong>Disable Fast Startup</strong></li>
<li><strong>Disable the USB Selective Suspend Setting</strong></li>
<li><strong>Remove USB Device and Scan for Hardware Changes</strong></li>
<li><strong>Update Windows 10</strong></li>
</ul>
<h2 id="heading-usb-hardware-fault">USB Hardware Fault</h2>
<p>The “Device Descriptor Request Failed” issue may have been caused by a hardware issue. We can easily test that the issue stems from a hardware issue and not an operating system related issue by performing the following checks:</p>
<p>First, plug the relevant device into a different USB port on the same computer. For good measure try a few USB ports. If the relevant device is working when plugged into another USB port, this means that the source of the issue is likely the USB port used when the issue arrises. </p>
<p>In this case you can simply mark the USB port causing the issue as faulty, and use the USB port that works. You also may wish to replace the offending USB port at some stage.</p>
<p>Second, you can plug the relevant device into a USB port on a different computer. If the device doesn’t work on a different computer, this points to the device itself being the issue. Your only solution in this case may be to repair or replace the device itself.</p>
<h2 id="heading-run-hardware-and-devices-troubleshooter">Run Hardware and Devices Troubleshooter</h2>
<p>Windows provides us with a very convenient facility that you can use for performing troubleshooting. You are able to use this facility to trouble shoot possible hardware issues. </p>
<p>Follow these steps to use the <strong>Troubleshooter</strong> facility:</p>
<ul>
<li>Firstly invoke the “Run” box. You can do this by pressing Windows key + R.</li>
<li>Enter the following command into the “Run” box: <strong>msdt.exe -id DeviceDiagnostic</strong></li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-235.png" alt="Image" width="600" height="400" loading="lazy"></p>
<ul>
<li>Press the <strong>OK</strong> button.</li>
<li>Select Advanced – and make sure that the “Apply repairs automatically” checkbox is checked. Press the “Next” button and follow the instructions to preform the troubleshooting task.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-236.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-uninstall-and-update-usb-device-driver">Uninstall and Update USB Device Driver</h2>
<p>To uninstall the USB device driver we can use the <strong>Device Manager</strong> facility provided by windows. To run <strong>Device Manager</strong>, follow these steps:</p>
<ul>
<li>First, invoke the “Run” box. One way to do this is to press <strong>Windows key + R</strong>.</li>
<li>Enter the following command into the “Run” box: <strong>devmgmt.msc</strong>. Then press the <strong>OK</strong> button.</li>
<li>Within the tree structure presented in the <strong>Device Manager</strong> dialog box, expand the <strong>Universal Serial Bus controllers</strong> node<strong>.</strong></li>
<li>From the expanded list of nodes, select the node marked “Unknown USB Device (Device Descriptor Request Failed)”</li>
<li>Right click this node and select <strong>Uninstall device</strong> from the context menu presented to you.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-237.png" alt="Image" width="600" height="400" loading="lazy"></p>
<ul>
<li>Once the uninstall operation has completed, reboot your computer. This will result in the driver being reinstalled which may also result in your issue being fixed.</li>
</ul>
<h2 id="heading-disable-fast-startup">Disable Fast Startup</h2>
<p>One possible cause of the “Device Descriptor Request Failed” issue could be from a feature in Windows designed to speed up the boot process of your computer. Sometimes, this “Fast Startup" feature can keep your Operating System from detecting USB devices. </p>
<p>Luckily we have the ability to turn this feature off. The “Fast Startup” feature is a “nice to have” feature and is it is recommended to have this feather turned on, but it is not an essential feature. </p>
<p>So to turn off the feature, follow these steps:</p>
<ul>
<li>Press Windows Key + R to invoke the “Run” box.</li>
<li>In the “Run” box type “control” and click the “OK” button to open Control Panel</li>
<li>In the search box of your Control Panel type “Power options” and then click “Change what the power buttons do”</li>
<li>Under the heading, “Define power buttons and turn on password protection”, click the link labelled, “Change settings that are currently unavailable”</li>
<li>Make sure that the “Turn on fast startup (recommended)” checkbox is unchecked. Click the “Save changes” button</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-238.png" alt="Image" width="600" height="400" loading="lazy"></p>
<ul>
<li>Restart your computer and see if this possible solution has fixed your USB device issue.</li>
</ul>
<h2 id="heading-disable-the-usb-selective-suspend-setting">Disable the USB Selective Suspend Setting</h2>
<p>Sometimes the USB port is put into low-power mode when the “USB selective suspend” setting is enabled. This can cause abnormal behaviour when connecting a device to a USB port, which can result in the “Device Descriptor Request Failed” issue occurring. </p>
<p>We are able to safely disable this feature, and by doing so potentially solve the “Device Descriptor Request Failed” issue. </p>
<p>To disable the “USB selective suspend” setting, follow these steps.</p>
<ul>
<li>Press Windows Key + R to invoke the “Run” box.</li>
<li>In the “Run” box, type “control” and click the “OK” button to open Control Panel</li>
<li>In your Control Panel find and click “Power Options”</li>
<li>Click the “Change plan settings” link</li>
<li>Click the “Change advanced power settings” link</li>
<li>Find and expand the “USB settings” node in the tree structure found on the "Advanced settings" tab.</li>
<li>Expand the “USB selective suspend setting” child node.</li>
<li>Make sure that “Disabled” is selected in the relevant dropdown list for both ”On battery” and “Plugged in”.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-239.png" alt="Image" width="600" height="400" loading="lazy"></p>
<ul>
<li>Click the “Ok” button</li>
<li>Reboot your computer</li>
<li>Once your computer has been rebooted, test to see if the “Device Descriptor Request Failed” issue has been resolved.</li>
</ul>
<h2 id="heading-remove-usb-device-and-scan-for-hardware-changes">Remove USB Device and Scan for Hardware Changes</h2>
<ul>
<li>Launch <strong>Device Manager</strong> by pressing Windows Key + R to launch the “Run” box, then type  <strong>devmgmt.msc</strong> in the "Run" box and press the “OK” button.</li>
<li>Unplug the problematic device from the relevant USB port.</li>
<li>From within the <strong>Device Manager</strong> dialog, click the “Scan for hardware changes” button on the toolbar. You can identify the relevant button by hovering your mouse pointer over the button whereby its tooltip text will display the text “Scan for hardware changes”.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-240.png" alt="Image" width="600" height="400" loading="lazy"></p>
<ul>
<li>When the system recognises hardware changes, plug in the relevant USB device and test whether the problem has been fixed</li>
</ul>
<h2 id="heading-update-windows">Update Windows</h2>
<p>Installing the latest update for Windows may fix the “Device Descriptor Request Failed” issue. To install the latest windows update you can follow these steps:</p>
<ul>
<li>Open the Settings App by pressing Windows key + I</li>
<li>Click the "Update &amp; Security" option</li>
<li>Select the “Windows Update” option</li>
<li>Click the “Check for updates” button</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-241.png" alt="Image" width="600" height="400" loading="lazy"></p>
<ul>
<li>Restart Computer and test to see if the “Device Descriptor Request Failed” issue still occurs (change)</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The “Device Descriptor Request Failed” issue can cause a lot of frustration and even heart ache in my poor mother's case where it prevented her from viewing family photos. </p>
<p>Don’t despair – hopefully this article provides you with an effective remedy for the issue.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ DNS Server Not Responding – How to Fix the Error in Windows 10 ]]>
                </title>
                <description>
                    <![CDATA[ I think it's safe to say that the vast majority of professionals depend on the internet these days.  So being denied access to the internet when you are trying to mine nuggets of valuable information from your go-to web sites can be quite an ordeal. ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-fix-dns-server-not-responding-error-windows-10/</link>
                <guid isPermaLink="false">66b0c5886e47f92ed2d0bf25</guid>
                
                    <category>
                        <![CDATA[ dns ]]>
                    </category>
                
                    <category>
                        <![CDATA[ error ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Windows ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Windows 10 ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Gavin Lon ]]>
                </dc:creator>
                <pubDate>Fri, 30 Sep 2022 15:00:47 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/09/DNS-Issue-Main-Pic---pexels-yan-krukov-4458420.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>I think it's safe to say that the vast majority of professionals depend on the internet these days. </p>
<p>So being denied access to the internet when you are trying to mine nuggets of valuable information from your go-to web sites can be quite an ordeal. Especially when you are under pressure to complete a piece of urgently required work. </p>
<p>One particularly unwelcome cause of being denied access to the internet is the “DNS Server Not Responding” error. It’s like that old fable where a troll sits under a bridge and says “You shall not pass!”, or something about gobbling up those that wish to cross the bridge. </p>
<p>I’m happy to tell you that you should be able to defeat the troll and cross the bridge to internet access joy by following the simple trouble shooting steps discussed in this article.</p>
<h2 id="heading-what-is-the-dns-server-not-responding-error">What is the "DNS Server Not Responding" Error?</h2>
<p>The “DNS Server Not Responding” error is a fairly common issue and is generally easy to fix. There are many reasons why this issue may occur. But fundamentally it is caused because the DNS server that is contacted during the processes of loading a web page is unable to find the site that contains the web page that you have requested. </p>
<p>This article explores what may have triggered this issue to occur and how you may go about fixing the issue.</p>
<p>Firstly, I think it is a good idea to gain at least a basic understanding of the “DNS Server Not Responding” error. To do this, let’s first understand DNS. </p>
<p>DNS stands for Domain Name System. A simple explanation of DNS is that it is a decentralised storage of human readable internet addresses, like the ones with which you will almost certainly be familiar (for example www.amazon.com or www.netlix.com). </p>
<p>The DNS maps these human readable URLs to their appropriate IP (Internet Protocol) addresses. </p>
<p>IP addresses are much less human readable, but are essential for the inner workings of the internet. IP addresses uniquely identify computers on the internet. The IP address associated with the URL, www.netflix.com, might for example, look like this, 69.53.224.255. </p>
<p>It is clearly easier for you to remember “<a target="_blank" href="http://www.netflix.com">www.netflix.com</a>", rather than a string of numbers delimited by full stops, when you wish to access your favourite content on Netflix. So the DNS facilitates this for you, so that you don’t have to remember or manually lookup unfriendly strings of numeric data every time you wish to access a web site. </p>
<p>The common analogy to explain DSN is a telephone directory. Basically, as you would look up a telephone number using the name of the person you wish to call in a telephone directory, a similar look up is performed when you type in the URL (like www.amazon.com) of the web site you wish to view within your browser.</p>
<p>Thankfully you don’t have to manually look up the corresponding IP address for www.amazon.com, as this is performed behind the scenes for you automatically. </p>
<p>So the appropriate IP address is retrieved automatically every time you type in a URL into your browser. This IP address is then used to contact the appropriate server that hosts the relevant web site associated with the URL you have entered into your browser.</p>
<p>When the “DNS Server Not Responding” error occurs, this means that the decentralised naming systems responsible for automatically looking up the appropriate IP address based on the relevant hostname that you entered into you browser fails to respond. </p>
<p>There are many reasons why this error occurs, but fortunately there are also many solutions available to you to fix the issue. </p>
<p>An easy solution may be to simply change the web browser you are using or even simpler still, simply restart your computer. Yup, simply turning it off and then turning it on again could fix the issue. </p>
<p>However, if you are not so lucky and the problem still persists, don’t despair – there are many steps that you can take to find out the cause of the issue and subsequently fix it. </p>
<p>In this article you will learn a number of possible solutions to the “DNS Server Not Responding” error.</p>
<h2 id="heading-how-to-fix-dns-serger-not-responding">How to Fix "DNS Serger Not Responding"</h2>
<p>Below, I've listed out the ways that you can try using to fix the “DNS Server Not Responding” error. The subsequent sections of this article provide details on each of these methods:</p>
<ul>
<li>Use a Different Web Browser</li>
<li>Try Accessing a Web Site with a Different Device</li>
<li>Restart your Router</li>
<li>Investigate Possible Network Issues</li>
<li>Manually Set your DNS Server</li>
<li>Clear the DNS Cache</li>
<li>Disable Internet Protocol Version 6</li>
<li>Temporarily Deactivate your Firewall and Disable your Antivirus Software</li>
<li>Reset your DNS Settings</li>
<li>Update the Network Adapter Driver</li>
<li>Disable all Network Connections Except the Connection you are Using to Access the Internet</li>
<li>Restart your Computer in Safe Mode</li>
</ul>
<h3 id="heading-use-a-different-web-browser">Use a Different Web Browser</h3>
<p>A potential solution to the “DNS Server not Responding” issue that's really simple is to try accessing the relevant website using a different browser. </p>
<p>If, for example, you are using Microsoft Edge or Mozilla Firefox as your browser at the time that the issue occurs, try using a different browser like Google Chrome to access the relevant website.</p>
<p>If using a different browser solves the problem, then make the browser that works your default browser. But if the issue still persists, then we at least know that the browser you have been using is not the source of the issue and our investigation into finding a solution to the DNS Server not Responding” issue must continue…</p>
<h3 id="heading-try-accessing-a-website-with-a-different-device">Try Accessing a Website With a Different Device</h3>
<p>Try to use a different device connected to your home network to access the website you were trying to access when you received the error. </p>
<p>For example, use Wi-Fi from your mobile phone to access the relevant web site. If the issue persists, you know that the issue isn’t just with your primary device and the problem may have something to do with your router.</p>
<h3 id="heading-restart-your-router">Restart Your Router</h3>
<p>The “DNS Server not Responding” issue may occur simply due to data traffic. It may be that simply restarting your router can fix this issue. </p>
<p>You can restart your router by pressing the power button on your router. You can then unplug your router's power cable. Wait for about 30 seconds then plug your router into the power outlet again and press the power button to restart it.</p>
<h3 id="heading-investigate-possible-network-issues">Investigate Possible Network Issues</h3>
<p>Running network diagnostics may point to network issues as the root cause of the issue. </p>
<p>Running Network Diagnostic is very simple on a Windows 10 OS. You can do this by following these steps:</p>
<ul>
<li>Open Control Panel. One way to do this is press the <strong>Windows Key + R</strong> to activate the “Run” box, then type “control” in the text box presented in the “Run” box and hit the enter key.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/image-443.png" alt="Image" width="600" height="400" loading="lazy"></p>
<ul>
<li>Select the <strong>Network and Internet</strong> option presented within the Control Panel window.</li>
<li>Click the <strong>Network and Sharing Center</strong> option from within the “Network and Internet” window.</li>
<li>Click the <strong>Troubleshoot problems</strong> option presented under the "Change your network settings” heading within the “Network and Sharing Center” window.</li>
<li>Click <strong>Additional troubleshooters</strong> -&gt; <strong>Internet Connections</strong> -&gt; <strong>Run the troubleshooter</strong></li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/image-457.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The next step is to wait for the troubleshooter task to finish. If you are presented with any error messages, simply follow the steps on how to fix the relevant network issue.</p>
<h3 id="heading-manually-set-your-dns-server">Manually Set Your DNS Server</h3>
<p>The source of your issue may be that your DNS server is down. In this case you’ll be pleased to know that you are able to manually change your DNS server. </p>
<p>You can change your DNS server to, for example, Googles Public DNS or CloudFlare’s public DNS. To change your DNS server, follow these steps:</p>
<ul>
<li>Invoke your Control Panel. One way to invoke your Control Panel is to activate your Start Menu and search for the Control Panel.</li>
<li>In the Control Panel window click the <strong>Network and Internet</strong> option.</li>
<li>In the <strong>Network and Internet</strong> window, click the <strong>Network and Sharing Center</strong> option.</li>
<li>On the  <strong>Network and Sharing Center</strong> window click on your active connection. For example, click the “ethernet” option if this is the connection currently being used or click the “Wi-Fi” option if it is clear that this is your active connection.</li>
<li>In the dialog box that is presented to you, click the “Properties” button.</li>
<li>In the dialog presented to you, you’ll see a list is presented under the “The connection uses the following items” heading.</li>
<li>In this list, select the list item labelled “Internet protocol version 4 (TCP/IPv4)” then click the “Properties” button.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/image-445.png" alt="Image" width="600" height="400" loading="lazy"></p>
<ul>
<li>You will be presented with another dialog box where you’ll see two fields. One will be labelled “Preferred DNS Server”, and the other which is directly under this field will be labelled “Alternate DNS Server”.</li>
<li>First click the <strong>Use the following DNS server addresses</strong> radio button.</li>
<li>To use Googles Public DNS server, enter 8.8.8.8 in the field labelled “Preferred DNS Server” and enter 8.8.4.4 into the field labelled “Alternate DNS Server”.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/image-446.png" alt="Image" width="600" height="400" loading="lazy"></p>
<ul>
<li>You are also able to use CloudFlare’s DNS server for the same purpose. CloudFlare’s DNS address is simply 1.1.1.1</li>
<li>Once you have entered your desired DNS server settings, ensure that the “Validate settings upon exit” checkbox is checked.</li>
<li>Click the “OK” button to save your new DNS server settings.</li>
<li>Restart your computer.</li>
</ul>
<h3 id="heading-clear-the-dns-cache">Clear the DNS Cache</h3>
<p>You are able to flush the DNS cache which may resolve the “DNS Server not Responding” issue. This action will clear IP addresses and other DNS related data from  your cache.</p>
<p>You can clear the DNS cache by running a command using your command prompt.</p>
<p>One way to invoke the command prompt is to press <strong>Window Key + R</strong> to invoke the “Run” box. Type “cmd” within the “Run” box and press <strong>shift+ctrl+enter</strong> to run the command prompt as an administrator.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/image-458.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>At the command prompt, type in the following command: “ipconfig /flushdns” and them press the enter key. If the command has executed successfully, you'll see the appropriate message in the command window.</p>
<h3 id="heading-disable-internet-protocol-version-6">Disable Internet Protocol Version 6</h3>
<p>At the time of writing this article, Internet Protocol Version 6 is the latest version of the internet protocol. Disabling the Internet Protocol Version 6 will not have detrimental effects on your computer’s operations, but it's been known to fix the “DNS Server not Responding” issue.</p>
<p>To disable the Internet Protocol version 6 on a Windows 10 operating system, just follow these steps:</p>
<ul>
<li>Go to <strong>Control Panel</strong> -&gt; <strong>Network and Internet</strong> -&gt; <strong>Network and Sharing Center</strong></li>
<li>Click on the relevant connection, for example “Wi-Fi”</li>
<li>Click the “Properties” button on the dialog that is presented to you.</li>
<li>In the list presented under the “This connection uses the following items” heading, uncheck the item labelled “Internet Protocol Version 6 (TCP/IPv6)”.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/image-448.png" alt="Image" width="600" height="400" loading="lazy"></p>
<ul>
<li>Press the “OK button”</li>
</ul>
<h3 id="heading-temporarily-deactivate-your-firewall-and-disable-antivirus">Temporarily Deactivate your Firewall and Disable Antivirus</h3>
<p>If your firewall is Defender, you can follow these steps to disable it:</p>
<ul>
<li>To open control panel, press <strong>Windows Key + R</strong> to activate the “Run” box, then type “control” in the text box presented in the “Run” box and hit the enter key.</li>
<li>In the top right hand text box, type in “win”</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/image-459.png" alt="Image" width="600" height="400" loading="lazy"></p>
<ul>
<li>An option labelled "Windows Defender Firewall” should appear in the search results. Click the “Windows Defender Firewall” option.</li>
<li>Click the “Allow an app or feature through Windows Defender Firewall” option.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/image-462.png" alt="Image" width="600" height="400" loading="lazy"></p>
<ul>
<li>Click the “Change settings” button.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/image-461.png" alt="Image" width="600" height="400" loading="lazy"></p>
<ul>
<li>From the list presented to you within the dialog box that has just been invoked, find the browser that you are using, for example Google Chrome. Then make sure that both the private and public checkboxes next to the relevant item are checked.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/image-466.png" alt="Image" width="600" height="400" loading="lazy"></p>
<ul>
<li>Once you've done this, try to access the relevant website using the relevant browser and see if the issue has been fixed.</li>
</ul>
<p>There is a chance that your firewall was preventing you from accessing external data through your browser. </p>
<p>Note that it is not recommended to leave your operating system unprotected by reliable antivirus software indefinitely. Disabling your antivirus software in this instance is only recommended for testing if the relevant antivirus software is the cause of the “DNS Server not Responding” issue. </p>
<p>To temporarily turn off Microsoft Defender antivirus protection, follow these steps:</p>
<ul>
<li>Select Start and then type in "Windows Security” in order to search for the relevant application.</li>
<li>Select <strong>Windows Security App</strong> from the search results.</li>
<li>Go to <strong>Virus &amp; Threat Protection</strong>.</li>
<li>Under <strong>Virus &amp; threat protection settings</strong> select <strong>Manage settings.</strong></li>
<li>Switch <strong>Real-time protection</strong> off.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/image-467.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Attempt to access the relevant website through the relevant browser to test if the “DNS Server not Responding” issue still occurs.</p>
<h3 id="heading-reset-dns-settings">Reset DNS Settings</h3>
<p>To reset your DNS Settings, follow these steps:</p>
<ul>
<li>Run the command prompt as an administrator. To do this activate the “Run” box by pressing <strong>Windows key + R</strong>.</li>
<li>In the run box type “cmd” and press <strong>shift + ctrl + enter</strong></li>
<li>Type the following commands in the command prompt. After entering each command press the enter key, so that each command is run individually.</li>
</ul>
<p><code>ipconfig /registerdns</code></p>
<p><code>ipconfig /release</code></p>
<p><code>Ipconfig /renew</code></p>
<p><code>netsh winsock reset</code></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/image-465.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Once you have run these commands, close the command prompt and restart your computer.</p>
<h3 id="heading-update-the-network-adapter-driver">Update the Network Adapter Driver</h3>
<p>You can manually update your network adapter driver, but it is much easier to automate this task. </p>
<p>You can automate this through the use of free software like “Driver Easy” (https://www.drivereasy.com/download-free-version/). Simply download the free version of this software. </p>
<p>Make sure that before you run the free version of the Driver Easy software that you create a system restore point. This provides you with insurance, so in the unlikely event that you encounter a nasty surprise that adversely effects your computer, that you are able to return your Windows OS back to the state that it was in before you ran the Driver Easy software and encountered an unexpected issue.</p>
<p>To use the Driver Easy software, follow these steps:</p>
<ul>
<li>Run the software</li>
<li>Click the “Scan Now” button</li>
<li>Press the “Update” button next to any outdated drivers.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/image-455.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-disable-all-network-connections-except-for-the-connection-that-you-are-using">Disable all Network Connections Except for the Connection that you are Using</h3>
<p>Disabling the additional network connections you may have setup on your computer (other than, for example, the Wi-Fi connection that you are using to access the internet) might fix the “DNS Server not Responding” issue. </p>
<p>To disable the relevant network connection, follow these steps:</p>
<ul>
<li>Firstly you must access your Network Connections. To access your Network Connections, press <strong>Windows Key + R</strong> to invoke the “Run” box</li>
<li>In the “Run” box type in “ncpa.cpl” and press enter.</li>
<li>Right click the relevant network connection and select “Disable” from the relevant context menu. Repeat this action until all connections except for the Wi-Fi connection you are using are disabled.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/image-456.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-restart-your-computer-in-safe-mode">Restart your Computer in Safe Mode</h3>
<p>When you start your computer in Safe Mode, this means the Windows operating system loads with a limited set of drivers and files. This can help you diagnose what is causing your “DNS Server not Responding” issue through a process of illumination (as it were). </p>
<p>So to start your PC in Safe Mode, follow these steps:</p>
<ul>
<li>Press the <strong>Windows Key + I</strong> to open Settings.</li>
<li>Select <strong>Update &amp; Security</strong> -&gt; <strong>Recovery</strong></li>
<li>Under <strong>Advanced startup</strong>, select <strong>Restart Now</strong></li>
<li>Once your PC has startup to the “Choose an option” screen, select <strong>Troubleshoot</strong> -&gt;  <strong>Advanced options</strong> -&gt; <strong>Startup Settings</strong> -&gt; <strong>Restart</strong></li>
<li>Once your PC has restarted you’ll see a list of options</li>
<li>Select <strong>5</strong> or press <strong>F5</strong> for Safe Mode with Networking.</li>
</ul>
<p>Try to access the web site that resulted in you getting the “DNS Server not Responding” issue. If the problem does not occur in safe mode this means that additional software may be the cause of the issue. </p>
<p>You can uninstall any additional software from your PC, one by one, and then test to see if the issue still occurs. If the issue does not occur after uninstalling particular software, this means that it is likely that this software was interfering with your internet access.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The “DNS Server not Responding” issue is relatively common and thankfully it is also relatively easy to fix. </p>
<p>It can be incredibly inconvenient to be denied access to the internet but hopefully the potential solutions outlined in this article will help you to once again have access to your favorite web sites.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Kernel Security Check Failure – How to Restart the Kernel in Windows 10 ]]>
                </title>
                <description>
                    <![CDATA[ I’ve been a professional software engineer for many years, and I can testify that there are few things worse than getting the dreaded BSOD (Blue Screen of Death). Especially when you are about to write a piece of mind bending code at 2am to meet a lo... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/kernel-security-check-failure-how-to-restart-the-kernel-in-windows-10/</link>
                <guid isPermaLink="false">66b0c58a374aa69009200c24</guid>
                
                    <category>
                        <![CDATA[ Windows ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Windows 10 ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Gavin Lon ]]>
                </dc:creator>
                <pubDate>Wed, 14 Sep 2022 15:41:50 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/09/ScreenShot1_BSOD_Anger.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>I’ve been a professional software engineer for many years, and I can testify that there are few things worse than getting the dreaded BSOD (Blue Screen of Death). Especially when you are about to write a piece of mind bending code at 2am to meet a looming deadline. </p>
<p>That’s just my perspective as a software engineer, but let’s face it – using a computer these days is absolutely essential for most professionals. </p>
<p>The point is the blue screen of death is about as welcome as a pigeon on a chessboard at a world champion chess tournament under almost any circumstances.</p>
<h3 id="heading-what-youll-learn">What You'll Learn</h3>
<p>In this article, we are going to look at one particularly pernicious cause of the BDOS, the dreaded "Kernel Security Check Failure" issue. We'll also see how you can fix this, should you be faced with this abominable issue. </p>
<h2 id="heading-common-causes-for-the-bsod">Common Causes for the BSOD</h2>
<p>Common reasons you might get the "Kernel Security Check Failure" issue are corrupted system files, faulty hardware, or outdated drivers.</p>
<h3 id="heading-corrupted-system-files">Corrupted system files</h3>
<p>Malware is the most likely cause of corrupted system files. The nomenclature of ‘Malware’ is a contraction of the term ‘Malicious Software’. This is software deliberately designed to be intrusive and cause disruption when you're working on your computer. </p>
<p>You have probably heard of terms like virus, trojan horse virus, worms, spyware, ransom ware, and so on. These are all examples of malicious software, Malware.</p>
<h3 id="heading-faulty-hardware">Faulty hardware</h3>
<p>Faulty RAM (memory) or a corrupted or damaged hard disk drive could be the cause of the issue.</p>
<h3 id="heading-outdated-drivers">Outdated drivers</h3>
<p>Out of all the possible causes of this "Kernel Security Check Failure" issue, the most likely cause is outdated drivers. </p>
<p>The outdated drivers issue may have arisen from upgrading from an older version of Windows to Windows 10. The relevant driver may have worked perfectly on the older version of Windows but may be incompatible with Windows 10.</p>
<h2 id="heading-what-is-the-blue-screen-of-death">What is the Blue Screen of Death?</h2>
<p>Typically you become aware of the "Kernel Security Check Failure" issue during Windows startup. This is where Windows performs a check process. If, during this process, Windows detects corruption in any critical data structures, the Kernel_Security_check_failure error is thrown. </p>
<p>As you can see by the screenshot below there is very little detail about the error. Thankfully, the message does include a stop code (highlighted in yellow) to help identify why you're presented with the dreaded BSOD.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/image-347.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-fix-the-kernel-security-check-failure-error">How to Fix the Kernel Security Check Failure Error</h2>
<p>Fortunately there are many potential fixes available to resolve the "Kernel Security Check Failure" issue.  </p>
<p>To solve the issue, you can go through an investigation process in order to pinpoint the cause of the issue. Once you have learned the cause of the issue, you'll know which of the fixes to apply. </p>
<p>But a quick fix which is the first item in the list of possible fixes provided in this article might be as simple as updating your system to the latest version of Windows 10. </p>
<p>You can see below a list of fixes discussed in this article. The subsequent sections contain step by step instructions for each potential fix in the list.</p>
<ul>
<li>Update to the Latest Released Version of Windows 10 </li>
<li>Update Drivers that Need to be Updated</li>
<li>Check for Viruses</li>
<li>Investigate Possible Corrupted Windows File System</li>
<li>Test to see if Disabling Antivirus Software Fixes the Issue</li>
<li>Investigate Possible Issues with RAM</li>
<li>Investigate Possible Hard Disk Drive Issues</li>
<li>Test to see if Disabling Antivirus Software Fixes the Issue</li>
<li>Start PC in Safe Mode</li>
</ul>
<h3 id="heading-update-to-the-latest-released-version-of-windows-10">Update to the Latest Released Version of Windows 10</h3>
<p>This maybe the easiest way to fix the issue. To update Windows 10 to the latest version of Windows, you can take the following steps:</p>
<ul>
<li>Click Windows key + I to invoke the Settings App.</li>
<li>Click the “Update &amp; Security” tile.</li>
<li>Click the “Check for Updates” button (status information will be presented on the screen regarding the download and installation progress)</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/image-348.png" alt="Image" width="600" height="400" loading="lazy"></p>
<ul>
<li>After the update is complete, check to see if the BSOD still occurs.</li>
</ul>
<h3 id="heading-update-drivers-that-need-to-be-updated">Update Drivers that Need to be Updated</h3>
<p>One easy way to check for drivers with issues is by using Device Manager.</p>
<p>To invoke Device Manager, press the Windows key + X. In the dialog that will be presented to you, a tree structure is displayed.</p>
<p>If you expand all of the nodes in the tree structure it should be apparent as to which drivers need to be updated – you'll see an exclamation mark with a yellow background colour next to the nodes that represent the drivers that need to be updated.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/image-349.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>To update a driver, simply right click on the node that represents the relevant driver (that needs to be updated) and click the “Update driver” context menu item. </p>
<p>You'll then see two options: you can either select the option whereby Windows 10 will search for the driver automatically, or you can choose the manual option and search your computer for the relevant new driver file that may already exist on your computer.</p>
<p>The next step is to allow the driver installation update to complete.</p>
<p>You can then continue to check for other problematic drivers by inspecting Device Manager for nodes that contain exclamation marks with yellow backgrounds. If you find any more, you can update those drivers until all the problematic drivers have been appropriately updated.</p>
<p>Then you just need to restart your computer so that the changes created by the new drivers are completed. Hopefully this eliminates your BSOD issue.</p>
<p>If the issue still occurs, your investigation must continue…</p>
<h3 id="heading-check-for-viruses"><strong>Check for Viruses</strong></h3>
<p>You must ensure that you have installed the latest Windows updates on your PC and use the antivirus software to check for viruses. </p>
<p>If one or more viruses are found, take the necessary action to remove the virus or viruses from your computer.</p>
<h3 id="heading-investigate-possible-corrupted-windows-file-system">Investigate Possible Corrupted Windows File System</h3>
<p>You can use the System File checker (SFC) tool to fix corrupt system files. Below are the steps that you can follow in order to run the System File checker tool.</p>
<ul>
<li>From the desktop, use the Windows + R key to open the “Run” box</li>
<li>In the the “Run” box, type in “cmd” then press ctrl+shift+enter to launch the command prompt with administrative privileges.</li>
<li>Click the "Yes" button on the "User Account Control"ss (UAC) prompt</li>
<li>Type “SFC /scannow” in the command prompt window and press “Enter”.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/image-350.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The System file checker utility will check the integrity of Windows system files and will perform appropriate repair operations if required.</p>
<p>Reboot your computer after the process is completed.</p>
<h3 id="heading-test-to-see-if-disabling-antivirus-software-fixes-the-issue">Test to see if Disabling Antivirus Software Fixes the Issue</h3>
<p>Antivirus software, even though well-intentioned, can inadvertently block non-harmful services and apps from running correctly. </p>
<p>This method will tell you (as it were) that your antivirus software may be the cause of your issue – but please be aware that it is not recommended that you run your computer without the protection of appropriate antivirus software.</p>
<p>To temporarily disable your antivirus software, you can simply invoke the task manager window. You can do this by pressing ctrl+shift+escape on your keyboard.</p>
<p>If task manager loads in compact mode, click the “More details” option. Then select the "Startup" tab at the top of the "Task Manager" Window.</p>
<p>Find the name representing your antivirus application and click the relevant list item.</p>
<p>Then click the disable button that will be present in the right hand corner of the Task Manager window.</p>
<p>Finally, restart computer and see if the BSOD still appears. </p>
<p>Again, remember that even if this fixes the issue, you shouldn't run your computer without antivirus software. So you'll likely need to look into alternatives for protection.</p>
<h3 id="heading-investigate-possible-issues-with-ram">Investigate Possible Issues with RAM</h3>
<p>To identify RAM (memory) issues you can invoke the built-in Windows 10 scanner. To do this click on the search magnifying glass icon in the taskbar or press the Windows Key + S.</p>
<p>Type "Memory Diagnostics" in the search text box and run the first option presented in the search results.</p>
<p>In the popup dialog box that is presented, select “Restart now and check for problems (recommended)” option to kick off the diagnostic process.</p>
<p>During the boot process the memory diagnostic process will attempt to identify possible errors and issues regarding RAM. If issues are found, they will be reported to you.</p>
<h3 id="heading-investigate-possible-hard-disk-drive-issues">Investigate Possible Hard Disk Drive Issues</h3>
<p>You can scan your hard disks for any inconsistencies and errors using the check disk tool.</p>
<p>To run the check disk tool, make sure that you are logged onto windows with an administrator account. Then follow these steps:</p>
<ul>
<li>At the desktop, click Windows Key + R to launch the “Run” box.</li>
<li>In the "Run" box, type in “cmd” then press ctrl+shift+enter to run the command prompt as administrator.</li>
<li>Click the "Yes" button on the "User Account Control" (UAC) prompt.</li>
<li>Type in “chkdsk c: /f” and press enter</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/image-351.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The “/f” option will attempt to fix any found errors</p>
<p>You could also include the “/r” option and the  “/x” option with this command. The “/r” option will locate bad sectors and recover any readable information, while the “/x” option forces the disk drive (about to be checked) to dismount before the utility begins a scan.</p>
<h3 id="heading-start-pc-in-safe-mode">Start PC in Safe Mode</h3>
<p>You can start your PCs in safe mode so that Windows 10 is booted with minimal files and drivers. To boot up Windows 10 in safe mode, you can follow these steps:</p>
<ul>
<li>Press Windows Key + I to invoke the Settings App.</li>
<li>Under the "Update &amp; Security" heading, select the "Recovery" tab.</li>
<li>Under the "Advanced Startup" heading in the right pane, press the "Restart Now" button.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/image-352.png" alt="Image" width="600" height="400" loading="lazy"></p>
<ul>
<li>After the PC restarts to the “Choose an option<strong>”</strong> screen, select Troubleshoot &gt; Advanced options &gt; Startup Settings &gt; Restart.</li>
</ul>
<p>After the PC restarts, you are presented with a list of options. Select “4” or press “F4” to start PC in Safe Mode. Or if you need to use the internet, you can select <strong>“</strong>5<strong>”</strong> or press <strong>“</strong>F5<strong>”</strong> for Safe Mode with Networking. </p>
<p>If the issue does not occur in safe mode, this means that the default settings and basic device drivers aren't causing the issue. </p>
<p>Assuming the problem does not occur in safe mode, you now know that the issue must be caused by an additional driver or application that runs in normal mode.</p>
<p>Using a process of elimination, you can now focus on the relevant additional drivers and applications. You can systematically uninstall each of the relevant applications starting with the most recently installed ones and working your way from most recently installed to the least recently installed. </p>
<p>With each uninstall you can test for the problem. This will hopefully pinpoint the application or program that was the cause of the issue. Then you can uninstall the relevant software to hopefully get rid of the issue.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In conclusion, the Kernel Security Check Failure issue can be a huge inconvenience. But hopefully the steps provided in this article will help you fix the issue.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
