<?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[ C - 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[ C - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Tue, 06 Oct 2026 12:34:49 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/c/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ The Design Patterns Handbook: Learn Popular Design Patterns with C# Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ Design patterns are reusable solutions to common problems in software design. Think of them as blueprints: not finished code, but proven templates you can adapt to solve a specific problem in your own ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-design-patterns-handbook-learn-popular-design-patterns-with-c-code-examples/</link>
                <guid isPermaLink="false">6a9eec68a0d0c091f35da7b8</guid>
                
                    <category>
                        <![CDATA[ design patterns ]]>
                    </category>
                
                    <category>
                        <![CDATA[ C ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software architecture ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Isaiah Clifford Opoku ]]>
                </dc:creator>
                <pubDate>Mon, 07 Sep 2026 16:55:04 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/4b19ec2c-2756-44d4-9a96-a5f196fdaae3.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Design patterns are <strong>r</strong>eusable solutions to common problems in software design. Think of them as blueprints: not finished code, but proven templates you can adapt to solve a specific problem in your own codebase.</p>
<p>This handbook serves as a practical guide to understanding software design patterns. I wrote it for every developer, regardless of the language you program in. Examples are written in C#, but every concept here applies equally to Python, Java, TypeScript, Go, and beyond.</p>
<p>The source code lives at <a href="https://github.com/Clifftech123/design-patterns-handbook">github.com/Clifftech123/design-patterns-handbook</a>.</p>
<h3 id="heading-things-to-keep-in-mind">Things to Keep in Mind:</h3>
<ul>
<li><p><strong>Design patterns aren't code.</strong> They're a way of <em>thinking</em> about how to structure your code. They're a tool, not a silver bullet, for solving specific design problems.</p>
</li>
<li><p><strong>The concepts are universal.</strong> The examples here are written in C#, but the same patterns exist in every language. If you write Python, Java, Go, or TypeScript, you're already using some of these without knowing it.</p>
</li>
<li><p><strong>There's no one-size-fits-all pattern.</strong> Each pattern exists to address a particular kind of problem. Understanding <em>what problem a pattern solves</em> is more important than memorizing the implementation.</p>
</li>
</ul>
<p>I use C# here as the teaching language because it's clear, readable, and widely understood. The goal of this handbook is for you to walk away understanding the pattern itself, not just the C# code.</p>
<p>There are three main types of design patterns: Creational, Structural, and Behavioral. We'll look at each one in turn here, starting with Creational.</p>
<h3 id="heading-what-well-cover">What We'll Cover:</h3>
<ul>
<li><p><a href="#heading-things-to-keep-in-mind">Things to Keep in Mind</a></p>
</li>
<li><p><a href="#heading-creational-design-patterns">Creational Design Patterns</a></p>
<ul>
<li><p><a href="#heading-1-singleton-design-pattern">1. Singleton Design Pattern</a></p>
</li>
<li><p><a href="#heading-2-the-factory-method">2. The Factory Method</a></p>
</li>
<li><p><a href="#heading-3-the-abstract-factory-design-pattern">3. The Abstract Factory Design Pattern</a></p>
</li>
<li><p><a href="#heading-4-the-builder-design-pattern">4. The Builder Design Pattern</a></p>
</li>
<li><p><a href="#heading-5-the-prototype-design-pattern">5. The Prototype Design Pattern</a></p>
</li>
</ul>
</li>
<li><p><a href="#heading-structural-design-patterns">Structural Design Patterns</a></p>
<ul>
<li><p><a href="#heading-1-the-adapter-design-pattern">1. The Adapter Design Pattern</a></p>
</li>
<li><p><a href="#heading-2-the-bridge-design-pattern">2. The Bridge Design Pattern</a></p>
</li>
<li><p><a href="#heading-3-the-composite-design-pattern">3. The Composite Design Pattern</a></p>
</li>
<li><p><a href="#heading-4-the-decorator-design-pattern">4. The Decorator Design Pattern</a></p>
</li>
<li><p><a href="#heading-5-the-facade-design-pattern">5. The Facade Design Pattern</a></p>
</li>
<li><p><a href="#heading-6-the-flyweight-design-pattern">6. The Flyweight Design Pattern</a></p>
</li>
<li><p><a href="#heading-7-the-proxy-design-pattern">7. The Proxy Design Pattern</a></p>
</li>
</ul>
</li>
<li><p><a href="#heading-behavioral-design-patterns">Behavioral Design Patterns</a></p>
<ul>
<li><p><a href="#heading-1-the-chain-of-responsibility-design-pattern">1. The Chain of Responsibility Design Pattern</a></p>
</li>
<li><p><a href="#heading-2-the-command-design-pattern">2. The Command Design Pattern</a></p>
</li>
<li><p><a href="#heading-3-the-interpreter-design-pattern">3. The Interpreter Design Pattern</a></p>
</li>
<li><p><a href="#heading-4-the-iterator-design-pattern">4. The Iterator Design Pattern</a></p>
</li>
<li><p><a href="#heading-5-the-mediator-design-pattern">5. The Mediator Design Pattern</a></p>
</li>
<li><p><a href="#heading-6-the-memento-design-pattern">6. The Memento Design Pattern</a></p>
</li>
<li><p><a href="#heading-7-the-observer-design-pattern">7. The Observer Design Pattern</a></p>
</li>
<li><p><a href="#heading-8-the-state-design-pattern">8. The State Design Pattern</a></p>
</li>
<li><p><a href="#heading-9-the-strategy-design-pattern">9. The Strategy Design Pattern</a></p>
</li>
<li><p><a href="#heading-10-the-template-method-design-pattern">10. The Template Method Design Pattern</a></p>
</li>
<li><p><a href="#heading-11-the-visitor-design-pattern">11. The Visitor Design Pattern</a></p>
</li>
</ul>
</li>
<li><p><a href="#heading-conclusion">Conclusion</a></p>
<ul>
<li><a href="#heading-a-few-things-worth-remembering">A few things worth remembering</a></li>
</ul>
</li>
</ul>
<h2 id="heading-creational-design-patterns">Creational Design Patterns</h2>
<p>Simply put, Creational patterns are all about <strong>how objects are created</strong>. They can be divided into class-creation patterns, which use inheritance to decide which class to instantiate, and object-creation patterns, which use delegation to get the job done.</p>
<p>Wikipedia describes them as:</p>
<blockquote>
<p><em>"A creational pattern aims to separate a system from how its objects are created, composed, and represented. They increase the system's flexibility in terms of the what, who, how, and when of object creation."</em></p>
<p><strong>(</strong><a href="https://en.wikipedia.org/wiki/Creational_pattern"><strong>Source</strong></a><strong>)</strong></p>
</blockquote>
<p>So Creational patterns keep the details of object creation <strong>hidden from the client code</strong>, making the system easier to manage and maintain.</p>
<p>They also abstract away how objects are created, composed, and represented, so the rest of your code doesn't need to care.</p>
<p>There are five Creational design patterns, which we'll go over one by one below:</p>
<ol>
<li><p><strong>Singleton</strong>: Ensures a class has only one instance and provides a global point of access to it.</p>
</li>
<li><p><strong>Factory Method</strong>: Defines an interface for creating an object, but lets subclasses decide which class to instantiate.</p>
</li>
<li><p><strong>Abstract Factory</strong>: Provides an interface for creating families of related or dependent objects without specifying their concrete classes.</p>
</li>
<li><p><strong>Builder</strong>: Separates the construction of a complex object from its representation, so the same construction process can produce different results.</p>
</li>
<li><p><strong>Prototype</strong>: Creates new objects by cloning an existing instance rather than building one from scratch.</p>
</li>
</ol>
<h3 id="heading-1-singleton-design-pattern">1. Singleton Design Pattern</h3>
<h4 id="heading-real-world-example">Real World Example:</h4>
<p>Think of the conductor of an orchestra. An orchestra has one conductor. Every musician on stage looks to that same conductor for direction: when to start, when to stop, how fast to play, and how loud to go.</p>
<p>The conductor is the single point of authority that all musicians connect to and take decisions from. You can't have two conductors standing at the front giving different instructions. That would cause chaos. No matter which musician needs guidance, they all reach the same one person.</p>
<p>That's exactly how the Singleton works in code: one instance, shared by everyone who needs it, making decisions from one place.</p>
<h4 id="heading-problems-it-solves">Problems it solves:</h4>
<ul>
<li><p>What if two musicians get different conductors giving different instructions? The performance falls apart. There must be one conductor that every musician looks to, without exception.</p>
</li>
<li><p>How does a musician find the conductor? They don't go searching. There's one well-known place everyone looks, and the same conductor is always there.</p>
</li>
<li><p>What stops someone from appointing a second conductor? The orchestra itself controls this. Once a conductor is on the podium, no second one can take it.</p>
</li>
</ul>
<p>In simple terms, there's only one instance of the class, and every part of the system that needs it gets access to that exact same instance (never a new one).</p>
<p>Here's how Wikipedia describes the Singleton pattern:</p>
<blockquote>
<p><em>"In object-oriented programming, the singleton pattern is a software design pattern that restricts the instantiation of a class to a singular instance. The pattern is useful when exactly one object is needed to coordinate actions across a system." (</em><a href="https://en.wikipedia.org/wiki/Singleton_pattern">Source</a>)</p>
</blockquote>
<h4 id="heading-programming-example">Programming Example:</h4>
<p>We'll model the analogy directly now. The <code>OrchestraConductor</code> is the Singleton: one instance, shared by all musicians, making all decisions.</p>
<pre><code class="language-csharp">public class OrchestraConductor
{
    // Step 1: Hold the one instance here
    private static OrchestraConductor _instance;

    // Step 2: Private constructor - nobody outside can do: new OrchestraConductor()
    private OrchestraConductor() { }

    // Step 3: The only way to get the conductor
    public static OrchestraConductor GetInstance()
    {
        if (_instance == null)
        {
            _instance = new OrchestraConductor();
        }

        return _instance;
    }

    // Decisions the conductor makes
    public void Start()                    =&gt; Console.WriteLine("Conductor: Begin playing.");
    public void Stop()                     =&gt; Console.WriteLine("Conductor: Stop playing.");
    public void SetTempo(string tempo)     =&gt; Console.WriteLine($"Conductor: Tempo is now {tempo}.");
}
</code></pre>
<p>Now let's see it in action:</p>
<pre><code class="language-csharp">// Violinist asks for the conductor
OrchestraConductor violinist = OrchestraConductor.GetInstance();

// Pianist asks for the conductor
OrchestraConductor pianist = OrchestraConductor.GetInstance();

// Are they talking to the same conductor?
Console.WriteLine(object.ReferenceEquals(violinist, pianist)); // True

violinist.SetTempo("Allegro");
pianist.Start();
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="language-yaml">True
Conductor: Tempo is now Allegro.
Conductor: Begin playing.
</code></pre>
<p>Both musicians got the <strong>same conductor</strong>. The constructor never ran twice. That is the Singleton pattern.</p>
<h4 id="heading-when-to-use-the-singleton-pattern">When to Use the Singleton Pattern</h4>
<p>Reach for Singleton when you need one shared resource that the whole application talks to, such as a logger, a configuration manager, or a database connection pool.</p>
<p>It's also a good idea when having more than one instance would cause incorrect behaviour or conflicting state.</p>
<p>And it's helpful when you want a global point of access to an object without passing it around everywhere.</p>
<h3 id="heading-2-the-factory-method">2. The Factory Method</h3>
<p>Think of a recruitment agency. A company calls the agency and says "we need a worker." The company doesn't go out and create the worker themselves. They just make the request.</p>
<p>The agency decides which specific person to send: a developer, a designer, or a tester, depending on what the company needs. The company doesn't know or care exactly who is coming. They just know the person will be able to do the job.</p>
<p>That's the Factory Method. Your code asks for an object. The Factory decides which specific type to create and hands it back. You work with it without needing to know exactly what it is under the hood.</p>
<h4 id="heading-problems-it-solves">Problems it solves:</h4>
<ul>
<li><p>The company shouldn't need to know who they're getting. They just need someone who can do the job. The agency handles the decision of whom to send. The company never has to worry about the details.</p>
</li>
<li><p>What if the company needs a different type of worker tomorrow? They call the same agency. The agency decides. The company's process doesn't change, only the agency's decision does.</p>
</li>
<li><p>What if a new type of worker needs to be introduced? A new specialist agency is created to handle that. Everything else stays exactly the same.</p>
</li>
</ul>
<p>In simple terms, we define an interface for creating an object, but let subclasses decide which class to instantiate. The factory method lets a class defer instantiation to subclasses.</p>
<p>Wikipedia describes it like this:</p>
<blockquote>
<p><em>"In object-oriented programming, the factory method pattern is a design pattern that uses factory methods to deal with the problem of creating objects without having to specify their exact classes. Factory methods can be specified in an interface and implemented by subclasses, or implemented in a base class and optionally overridden by subclasses." (</em><a href="https://en.wikipedia.org/wiki/Factory_method_pattern">Source</a>)</p>
</blockquote>
<h4 id="heading-programming-example">Programming Example:</h4>
<p>The agency is the factory. The worker types are the products. The company is the client.</p>
<pre><code class="language-csharp">// The worker interface - all workers can do a job
public interface IWorker
{
    void DoWork();
}
</code></pre>
<pre><code class="language-csharp">// The concrete workers
public class Developer : IWorker
{
    public void DoWork() =&gt; Console.WriteLine("Developer: Writing code.");
}

public class Designer : IWorker
{
    public void DoWork() =&gt; Console.WriteLine("Designer: Creating designs.");
}
</code></pre>
<pre><code class="language-csharp">// The base agency - declares the factory method
public abstract class RecruitmentAgency
{
    // This is the Factory Method - subclasses decide who to hire
    public abstract IWorker HireWorker();
}
</code></pre>
<pre><code class="language-csharp">// Concrete agencies - each one decides which worker to send
public class TechAgency : RecruitmentAgency
{
    public override IWorker HireWorker() =&gt; new Developer();
}

public class DesignAgency : RecruitmentAgency
{
    public override IWorker HireWorker() =&gt; new Designer();
}
</code></pre>
<p>Now let's see it in action:</p>
<pre><code class="language-csharp">// Company A needs a tech worker
RecruitmentAgency agency = new TechAgency();
IWorker worker = agency.HireWorker();
worker.DoWork();

// Company B needs a design worker
RecruitmentAgency agency2 = new DesignAgency();
IWorker worker2 = agency2.HireWorker();
worker2.DoWork();
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="language-yaml">Developer: Writing code.
Designer: Creating designs.
</code></pre>
<p>The company never used <code>new Developer()</code> or <code>new Designer()</code> directly. The agency made that decision. That is the Factory Method.</p>
<h3 id="heading-3-the-abstract-factory-design-pattern">3. The Abstract Factory Design Pattern</h3>
<h4 id="heading-real-world-example">Real World Example</h4>
<p>Think of a furniture store that sells collections. You walk in and choose a style: Modern or Victorian. Once you choose, everything you get comes from that same collection. The sofa, the chair, and the coffee table all match. The store ensures that you never walk out with a modern sofa paired with a Victorian chair. You don't pick individual pieces and hope they go together. The collection guarantees they will.</p>
<p>That's the Abstract Factory. You choose a family, and the Factory produces every object you need from that same family. Everything it gives you is guaranteed to work together.</p>
<h4 id="heading-problems-it-solves">Problems it solves:</h4>
<ul>
<li><p>What if a customer mixes furniture from different collections? The room looks inconsistent. The store solves this by grouping everything into collections. You pick one collection and everything comes from it.</p>
</li>
<li><p>What if the store wants to introduce a new collection? They create a new collection set. Every existing collection stays untouched. The customer's experience doesn't change, only the options grow.</p>
</li>
<li><p>What if different stores carry different collections? Each store is its own factory. A customer walks into any store and follows the same process. The store handles which specific pieces to provide.</p>
</li>
</ul>
<p>In simple terms, you provide an interface for creating families of related objects, without specifying their concrete classes.</p>
<p>Wikipedia describes it like this:</p>
<blockquote>
<p><em>"The abstract factory pattern provides a way to create families of related objects without imposing their concrete classes, by encapsulating a group of individual factories that have a common theme without specifying their concrete classes."</em></p>
<p><strong>Source:</strong> <a href="https://en.wikipedia.org/wiki/Abstract_factory_pattern">Wikipedia - Abstract factory pattern</a></p>
</blockquote>
<h4 id="heading-programming-example">Programming Example:</h4>
<p>The furniture store is the abstract factory. Modern and Victorian are the concrete factories. Sofa and Chair are the products.</p>
<pre><code class="language-csharp">// The product interfaces - every furniture type has a contract
public interface ISofa  { void Describe(); }
public interface IChair { void Describe(); }
</code></pre>
<pre><code class="language-csharp">// Modern collection
public class ModernSofa : ISofa
{
    public void Describe() =&gt; Console.WriteLine("Sofa: Sleek modern design.");
}

public class ModernChair : IChair
{
    public void Describe() =&gt; Console.WriteLine("Chair: Minimalist modern style.");
}
</code></pre>
<pre><code class="language-csharp">// Victorian collection
public class VictorianSofa : ISofa
{
    public void Describe() =&gt; Console.WriteLine("Sofa: Ornate Victorian design.");
}

public class VictorianChair : IChair
{
    public void Describe() =&gt; Console.WriteLine("Chair: Classic Victorian style.");
}
</code></pre>
<pre><code class="language-csharp">// The abstract factory - every store can produce a sofa and a chair
public interface IFurnitureFactory
{
    ISofa  CreateSofa();
    IChair CreateChair();
}
</code></pre>
<pre><code class="language-csharp">// Concrete factories - each one produces its own collection
public class ModernFurnitureFactory : IFurnitureFactory
{
    public ISofa  CreateSofa()  =&gt; new ModernSofa();
    public IChair CreateChair() =&gt; new ModernChair();
}

public class VictorianFurnitureFactory : IFurnitureFactory
{
    public ISofa  CreateSofa()  =&gt; new VictorianSofa();
    public IChair CreateChair() =&gt; new VictorianChair();
}
</code></pre>
<p>Now let's see it in action:</p>
<pre><code class="language-csharp">// Customer orders a Modern collection
IFurnitureFactory factory = new ModernFurnitureFactory();
ISofa  sofa  = factory.CreateSofa();
IChair chair = factory.CreateChair();
sofa.Describe();
chair.Describe();

// Customer orders a Victorian collection
IFurnitureFactory factory2 = new VictorianFurnitureFactory();
ISofa  sofa2  = factory2.CreateSofa();
IChair chair2 = factory2.CreateChair();
sofa2.Describe();
chair2.Describe();
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="language-yaml">Sofa: Sleek modern design.
Chair: Minimalist modern style.
Sofa: Ornate Victorian design.
Chair: Classic Victorian style.
</code></pre>
<p>Every piece came from the same collection. The client never used <code>new ModernSofa()</code> or <code>new VictorianChair()</code> directly. The factory kept the family together. That's the Abstract Factory.</p>
<h4 id="heading-when-to-use-abstract-factory">When to Use Abstract Factory:</h4>
<p>Use the Abstract Factory pattern when your system needs to work with multiple families of related objects and you need to ensure they're always used together.</p>
<p>It also works well when you want to swap out an entire family of objects in one place without touching the rest of your code.</p>
<p>And it's a good choice when you want to enforce consistency across related objects, so nothing from one family gets accidentally mixed with another.</p>
<h3 id="heading-4-the-builder-design-pattern">4. The Builder Design Pattern</h3>
<h4 id="heading-real-world-example">Real World Example</h4>
<p>Think of a tailor making a suit. Every customer that walks in goes through the same process: take measurements, choose the fabric, select the lining, pick the buttons, and decide on the lapel style.</p>
<p>The tailor follows those same steps for every order. But the finished suit is completely unique to each customer. A businessman walks out with a sharp formal suit. A wedding guest walks out with something entirely different. Same process, same tailor, but with different result every time.</p>
<p>That's the Builder. The construction process stays the same. What changes are the choices made at each step.</p>
<h4 id="heading-problems-it-solves">Problems it solves:</h4>
<ul>
<li><p>What if a suit had to be assembled all at once with no steps? You would have to know every detail upfront and get it all right in one go. The tailor breaks it down into steps so each decision is made clearly, one at a time.</p>
</li>
<li><p>What if two customers want completely different suits but go through the same tailor? The tailor follows the same process for both. The steps don't change, only the choices within each step.</p>
</li>
<li><p>What if a new suit style needs to be introduced? A new set of choices is defined for that style. The tailoring process itself stays untouched.</p>
</li>
</ul>
<p>In simple terms, you separate the construction of a complex object from its representation, so that the same construction process can create different results.</p>
<p>Wikipedia describes it like this:</p>
<blockquote>
<p><em>"The Builder pattern separates the construction of a complex object from its representation so that the same construction process can create different representations."</em> <a href="https://en.wikipedia.org/wiki/Builder_pattern">(Source)</a></p>
</blockquote>
<h4 id="heading-programming-example">Programming Example:</h4>
<p>The tailor is the director. The suit is the product. The builder handles the step-by-step construction.</p>
<pre><code class="language-csharp">// The product
public class Suit
{
    public string Fabric  { get; set; }
    public string Lining  { get; set; }
    public string Buttons { get; set; }

    public void Describe()
    {
        Console.WriteLine($"Suit: {Fabric} fabric, {Lining} lining, {Buttons} buttons.");
    }
}
</code></pre>
<pre><code class="language-csharp">// The builder - defines the steps
public interface ISuitBuilder
{
    void SetFabric();
    void SetLining();
    void SetButtons();
    Suit GetSuit();
}
</code></pre>
<pre><code class="language-csharp">// Business suit builder
public class BusinessSuitBuilder : ISuitBuilder
{
    private Suit _suit = new Suit();

    public void SetFabric()  =&gt; _suit.Fabric  = "Dark wool";
    public void SetLining()  =&gt; _suit.Lining  = "Silk";
    public void SetButtons() =&gt; _suit.Buttons = "Black horn";
    public Suit GetSuit()    =&gt; _suit;
}

// Wedding suit builder
public class WeddingSuitBuilder : ISuitBuilder
{
    private Suit _suit = new Suit();

    public void SetFabric()  =&gt; _suit.Fabric  = "Ivory linen";
    public void SetLining()  =&gt; _suit.Lining  = "Satin";
    public void SetButtons() =&gt; _suit.Buttons = "Pearl";
    public Suit GetSuit()    =&gt; _suit;
}
</code></pre>
<pre><code class="language-csharp">// The tailor - the director who runs the process
public class Tailor
{
    public Suit MakeSuit(ISuitBuilder builder)
    {
        builder.SetFabric();
        builder.SetLining();
        builder.SetButtons();
        return builder.GetSuit();
    }
}
</code></pre>
<p>Now let's see it in action:</p>
<pre><code class="language-csharp">Tailor tailor = new Tailor();

Suit businessSuit = tailor.MakeSuit(new BusinessSuitBuilder());
businessSuit.Describe();

Suit weddingSuit = tailor.MakeSuit(new WeddingSuitBuilder());
weddingSuit.Describe();
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="language-plaintext">Suit: Dark wool fabric, Silk lining, Black horn buttons.
Suit: Ivory linen fabric, Satin lining, Pearl buttons.
</code></pre>
<p>The same tailor, following the same process, creates two completely different suits. That is the Builder.</p>
<h4 id="heading-when-to-use-the-builder-design-pattern">When to Use the Builder Design Pattern</h4>
<p>Use the Builder pattern when an object has many parts or configurations and building it all at once would be confusing.</p>
<p>It's also a good choice when you want the same construction process to produce different results depending on the choices made at each step.</p>
<p>And reach for it when you want to keep the construction logic separate from the object itself, so each can change independently.</p>
<h3 id="heading-5-the-prototype-design-pattern">5. The Prototype Design Pattern</h3>
<h4 id="heading-real-world-example">Real World Example</h4>
<p>Imagine you're building a drawing application. Users can create shapes like circles, rectangles, or triangles, each with its own colour, size, and position.</p>
<p>Now imagine the user wants ten red circles of the same size placed across the canvas. Creating each one from scratch means repeating the same setup ten times. What if the shape is complex, with many configured properties? That becomes expensive and repetitive.</p>
<p>The Prototype pattern solves this by letting you take one fully configured shape and clone it. The clone starts as an exact copy. The user then moves it, recolours it, or resizes it independently. The original shape is never touched. This also means new shape types can be added at runtime without the application needing to know about them in advance.</p>
<h4 id="heading-problems-it-solves">Problems it solves:</h4>
<ul>
<li><p>Creating a new shape from scratch every time is expensive. If a shape has many properties, setting them all up repeatedly wastes resources. Cloning an already configured object is far cheaper.</p>
</li>
<li><p>The application shouldn't need to know the exact type of shape it's copying. At runtime, shapes can be added or removed dynamically. The app just calls clone and gets back a ready object, whatever type it happens to be.</p>
</li>
<li><p>Modifying a copy should never affect the original. Each cloned shape is fully independent. Changes to the copy stay with the copy.</p>
</li>
</ul>
<p>In simple terms, you can create new objects by copying an existing one. The copy starts identical to the original and can then be changed independently.</p>
<p>Wikipedia describes it like this:</p>
<blockquote>
<p><em>"The Prototype pattern is used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects." (</em><a href="https://en.wikipedia.org/wiki/Prototype_pattern">Source</a>)</p>
</blockquote>
<h4 id="heading-programming-example">Programming Example:</h4>
<p>Every shape knows how to clone itself. The application never calls <code>new Circle()</code> or <code>new Rectangle()</code> directly at runtime. It clones what already exists.</p>
<pre><code class="language-csharp">// The prototype interface - every shape must be able to clone itself
public abstract class Shape
{
    public string Colour { get; set; }
    public int    Size   { get; set; }

    public abstract Shape Clone();
    public abstract void  Describe();
}
</code></pre>
<pre><code class="language-csharp">// Concrete shapes
public class Circle : Shape
{
    public override Shape Clone()    =&gt; (Shape)this.MemberwiseClone();
    public override void  Describe() =&gt; Console.WriteLine($"Circle  | Colour: {Colour} | Size: {Size}");
}

public class Rectangle : Shape
{
    public override Shape Clone()    =&gt; (Shape)this.MemberwiseClone();
    public override void  Describe() =&gt; Console.WriteLine($"Rectangle | Colour: {Colour} | Size: {Size}");
}
</code></pre>
<p>Now let's see it in action:</p>
<pre><code class="language-csharp">// Create one configured circle
Circle original = new Circle { Colour = "Red", Size = 50 };

// Clone it instead of building from scratch
Shape clone1 = original.Clone();
Shape clone2 = original.Clone();

// Modify the clones independently
clone2.Colour = "Blue";

original.Describe();
clone1.Describe();
clone2.Describe();
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="language-plaintext">Circle  | Colour: Red  | Size: 50
Circle  | Colour: Red  | Size: 50
Circle  | Colour: Blue | Size: 50
</code></pre>
<p><code>clone2</code> changed to blue. The original stayed red. Each object is fully independent. That's the Prototype.</p>
<h4 id="heading-when-to-use-the-prototype-design-pattern">When to Use the Prototype Design Pattern:</h4>
<p>Use Prototype when creating a new object from scratch is expensive or complex and an existing object already has everything configured.</p>
<p>It's also helpful when the application needs to create objects at runtime without knowing their exact type in advance.</p>
<p>And it's great when you need many variations of an object and want to start from a known good state rather than rebuild every time.</p>
<h2 id="heading-structural-design-patterns">Structural Design Patterns</h2>
<p>Simply put, structural patterns are all about <strong>how classes and objects are composed to form larger structures</strong>. They use inheritance and composition to let you build flexible, efficient structures without having to rewrite everything from scratch.</p>
<p>Wikipedia describes them as:</p>
<blockquote>
<p><em>"In software engineering, structural patterns are design patterns that ease the design by identifying a simple way to realize relationships among entities." (</em><a href="https://en.wikipedia.org/wiki/Structural_pattern">Source</a>)</p>
</blockquote>
<p>Structural design patterns describe how objects and classes are combined to form <strong>larger, more complex structures</strong> while keeping those structures flexible and efficient.</p>
<p>They focus on composition over inheritance: how you connect things, not just what things are.</p>
<p>There are seven Structural design patterns:</p>
<ol>
<li><p><strong>Adapter</strong>: Converts one interface into another that a client expects, letting incompatible interfaces work together.</p>
</li>
<li><p><strong>Bridge</strong>: Decouples an abstraction from its implementation so the two can vary independently.</p>
</li>
<li><p><strong>Composite</strong>: Composes objects into tree structures to represent part-whole hierarchies, letting clients treat individual objects and compositions uniformly.</p>
</li>
<li><p><strong>Decorator</strong>: Attaches additional responsibilities to an object dynamically, as a flexible alternative to subclassing.</p>
</li>
<li><p><strong>Facade</strong>: Provides a simplified, unified interface to a complex subsystem.</p>
</li>
<li><p><strong>Flyweight</strong>: Uses sharing to efficiently support a large number of fine-grained objects.</p>
</li>
<li><p><strong>Proxy</strong>: Provides a surrogate or placeholder for another object to control access to it.</p>
</li>
</ol>
<h3 id="heading-1-the-adapter-design-pattern">1. The Adapter Design Pattern</h3>
<h4 id="heading-real-world-example">Real World Example</h4>
<p>Think of a language translator at a business meeting. A British CEO needs to address a Japanese team. The CEO speaks only English. The team speaks only Japanese. A translator sits between them, converting every English sentence into Japanese and delivering it to the team. Both sides keep speaking their own language. Neither the CEO nor the team change anything about how they communicate. The translator makes them compatible.</p>
<p>That's the Adapter. The client speaks one interface, while the other side speaks a different one. The Adapter sits between them and makes both sides work together without either having to change.</p>
<h4 id="heading-problems-it-solves">Problems it solves:</h4>
<ul>
<li><p>The CEO can't speak Japanese, and the team can't speak English. They're incompatible. The translator adapts one to the other without changing either side.</p>
</li>
<li><p>What if the CEO now needs to address a French team? A French translator is brought in. The CEO's process doesn't change. Only the translator changes.</p>
</li>
<li><p>What if an existing class has a useful method but the wrong interface? You wrap it in an adapter. The rest of the system talks to the adapter while the existing class stays untouched.</p>
</li>
</ul>
<p>In simple terms, you wrap an existing class with a new interface so the client can use it without any changes to either side.</p>
<p>Wikipedia describes it like this:</p>
<blockquote>
<p><em>"In software engineering, the adapter pattern is a software design pattern (also known as wrapper) that allows the interface of an existing class to be used as another interface. It is often used to make existing classes work with others without modifying their source code."</em> <a href="https://en.wikipedia.org/wiki/Adapter_pattern">(Source</a>)</p>
</blockquote>
<h4 id="heading-programming-example">Programming Example:</h4>
<p>The CEO is the client and the Japanese team member is the adaptee. They're useful, but they speak the wrong interface. The Translator is the adapter.</p>
<pre><code class="language-csharp">// What the CEO expects, someone who can receive a message in English
public interface IEnglishSpeaker
{
    void Speak(string message);
}
</code></pre>
<pre><code class="language-csharp">// The Japanese team member, speaks only Japanese (the adaptee)
public class JapaneseTeamMember
{
    public void SpeakJapanese(string message)
    {
        Console.WriteLine($"Team member (Japanese): {message}");
    }
}
</code></pre>
<pre><code class="language-csharp">// The Translator, adapts the Japanese speaker to the English interface
public class Translator : IEnglishSpeaker
{
    private readonly JapaneseTeamMember _teamMember;

    public Translator(JapaneseTeamMember teamMember)
    {
        _teamMember = teamMember;
    }

    public void Speak(string message)
    {
        string translated = TranslateToJapanese(message);
        _teamMember.SpeakJapanese(translated);
    }

    private string TranslateToJapanese(string english) =&gt; english switch
    {
        "Good morning, team."         =&gt; "おはようございます、チームの皆さん。",
        "Please review the proposal." =&gt; "提案書を確認してください。",
        _                             =&gt; $"[Japanese: {english}]"
    };
}
</code></pre>
<pre><code class="language-csharp">// The CEO, only knows how to talk to an IEnglishSpeaker
public class CEO
{
    private readonly IEnglishSpeaker _speaker;

    public CEO(IEnglishSpeaker speaker)
    {
        _speaker = speaker;
    }

    public void Address(string message)
    {
        Console.WriteLine($"CEO (English): {message}");
        _speaker.Speak(message);
    }
}
</code></pre>
<p>Now let's see it in action:</p>
<pre><code class="language-csharp">JapaneseTeamMember teamMember = new JapaneseTeamMember();
IEnglishSpeaker translator    = new Translator(teamMember);
CEO ceo = new CEO(translator);

ceo.Address("Good morning, team.");
ceo.Address("Please review the proposal.");
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="language-yaml">CEO (English): Good morning, team.
Team member (Japanese): おはようございます、チームの皆さん。
CEO (English): Please review the proposal.
Team member (Japanese): 提案書を確認してください。
</code></pre>
<p>The CEO never knew about <code>JapaneseTeamMember</code>. The team never knew about the CEO's interface. The <code>Translator</code> made both sides work together without touching either. That's the Adapter.</p>
<h4 id="heading-when-to-use-it">When to Use it</h4>
<p>Use Adapter when you want to use an existing class but its interface doesn't match what your code expects.</p>
<p>It's also helpful when you want to create a reusable class that cooperates with classes that don't have compatible interfaces.</p>
<p>And reach for it when you need to integrate a third-party library or legacy code without modifying it.</p>
<h3 id="heading-2-the-bridge-design-pattern">2. The Bridge Design Pattern</h3>
<h4 id="heading-real-world-example">Real World Example</h4>
<p>Think of a TV remote control and a television. The remote is one thing and the TV is another. You can have a basic remote or a smart remote. You can have a Sony TV or a Samsung TV. Any remote works with any TV you're not locked in. Buy a new Samsung TV, and your old remote still works. Buy a smart universal remote, and it works with every TV you own. Neither side needs to know the inner details of the other.</p>
<p>That's the Bridge. The abstraction (remote) and the implementation (TV) are two separate hierarchies that can grow and change completely independently of each other.</p>
<h4 id="heading-problems-it-solves">Problems it solves:</h4>
<ul>
<li><p>What if every remote was hardwired to one specific TV brand? You would need a SonyBasicRemote, a SamsungBasicRemote, a SonySmartRemote, a SamsungSmartRemote...and so on. One class for every combination. Adding one new TV brand would double your remote classes. The Bridge stops this explosion.</p>
</li>
<li><p>What if you want to add a new remote type without touching the TVs? With Bridge, you just create a new remote class. The TVs are untouched.</p>
</li>
<li><p>What if you want to add a new TV brand without touching the remotes? Same answer. You add a new TV class. Every existing remote already works with it.</p>
</li>
</ul>
<p>In simple terms, you split a large class into two separate hierarchies (the abstraction and the implementation) so each can be changed and extended without affecting the other.</p>
<p>Wikipedia describes it like this:</p>
<blockquote>
<p><em>"The bridge pattern is a design pattern used in software engineering that is meant to decouple an abstraction from its implementation so that the two can vary independently." (</em><a href="https://en.wikipedia.org/wiki/Bridge_pattern">Source</a>)</p>
</blockquote>
<h4 id="heading-programming-example">Programming Example:</h4>
<p>The remote control is the abstraction and the TV brand is the implementation. They're connected through a bridge (the <code>ITV</code> interface), but neither hierarchy depends on the other's details.</p>
<pre><code class="language-csharp">// The implementation interface — what any TV must be able to do
public interface ITV
{
    void TurnOn();
    void TurnOff();
    void SetChannel(int channel);
    void SetVolume(int volume);
}
</code></pre>
<pre><code class="language-csharp">// Concrete implementations — each brand handles things its own way
public class SonyTV : ITV
{
    public void TurnOn()           =&gt; Console.WriteLine("Sony TV: Powering on. BRAVIA display ready.");
    public void TurnOff()          =&gt; Console.WriteLine("Sony TV: Shutting down.");
    public void SetChannel(int ch) =&gt; Console.WriteLine($"Sony TV: Switching to channel {ch}.");
    public void SetVolume(int vol) =&gt; Console.WriteLine($"Sony TV: Volume set to {vol}.");
}

public class SamsungTV : ITV
{
    public void TurnOn()           =&gt; Console.WriteLine("Samsung TV: Turning on. Smart Hub loading.");
    public void TurnOff()          =&gt; Console.WriteLine("Samsung TV: Powering off.");
    public void SetChannel(int ch) =&gt; Console.WriteLine($"Samsung TV: Channel {ch} selected.");
    public void SetVolume(int vol) =&gt; Console.WriteLine($"Samsung TV: Volume at {vol}.");
}
</code></pre>
<pre><code class="language-csharp">// The abstraction — the remote holds a reference to whichever TV it controls
public abstract class RemoteControl
{
    protected ITV _tv;

    protected RemoteControl(ITV tv) { _tv = tv; }

    public abstract void TurnOn();
    public abstract void TurnOff();
    public abstract void SetChannel(int channel);
}
</code></pre>
<pre><code class="language-csharp">// Refined abstraction — a basic remote, does exactly what the TV does
public class BasicRemote : RemoteControl
{
    public BasicRemote(ITV tv) : base(tv) { }

    public override void TurnOn()           =&gt; _tv.TurnOn();
    public override void TurnOff()          =&gt; _tv.TurnOff();
    public override void SetChannel(int ch) =&gt; _tv.SetChannel(ch);
}

// Refined abstraction — a smart remote, adds its own behaviour on top
public class SmartRemote : RemoteControl
{
    public SmartRemote(ITV tv) : base(tv) { }

    public override void TurnOn()
    {
        Console.WriteLine("Smart Remote: Activating voice control.");
        _tv.TurnOn();
    }

    public override void TurnOff()
    {
        Console.WriteLine("Smart Remote: Saving watch history.");
        _tv.TurnOff();
    }

    public override void SetChannel(int ch)
    {
        Console.WriteLine("Smart Remote: Looking up channel guide.");
        _tv.SetChannel(ch);
    }

    public void SetVolume(int vol) =&gt; _tv.SetVolume(vol);
}
</code></pre>
<p>Now let's see it in action:</p>
<pre><code class="language-csharp">// Basic remote paired with a Sony TV
Console.WriteLine("--- Basic Remote + Sony TV ---");
RemoteControl basicSony = new BasicRemote(new SonyTV());
basicSony.TurnOn();
basicSony.SetChannel(5);
basicSony.TurnOff();

// Smart remote paired with a Samsung TV
Console.WriteLine("\n--- Smart Remote + Samsung TV ---");
SmartRemote smartSamsung = new SmartRemote(new SamsungTV());
smartSamsung.TurnOn();
smartSamsung.SetChannel(10);
smartSamsung.SetVolume(20);
smartSamsung.TurnOff();

// Swap freely — smart remote now with Sony, no code changes needed
Console.WriteLine("\n--- Smart Remote + Sony TV ---");
SmartRemote smartSony = new SmartRemote(new SonyTV());
smartSony.TurnOn();
smartSony.SetChannel(3);
smartSony.TurnOff();
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="language-yaml">--- Basic Remote + Sony TV ---
Sony TV: Powering on. BRAVIA display ready.
Sony TV: Switching to channel 5.
Sony TV: Shutting down.

--- Smart Remote + Samsung TV ---
Smart Remote: Activating voice control.
Samsung TV: Turning on. Smart Hub loading.
Smart Remote: Looking up channel guide.
Samsung TV: Channel 10 selected.
Samsung TV: Volume at 20.
Smart Remote: Saving watch history.
Samsung TV: Powering off.

--- Smart Remote + Sony TV ---
Smart Remote: Activating voice control.
Sony TV: Powering on. BRAVIA display ready.
Smart Remote: Looking up channel guide.
Sony TV: Switching to channel 3.
Smart Remote: Saving watch history.
Sony TV: Shutting down.
</code></pre>
<p>The same <code>SmartRemote</code> worked with both Sony and Samsung without any changes. Adding a new TV brand like LG means creating one new class, and every existing remote works with it immediately. That's the Bridge.</p>
<h4 id="heading-when-to-use-it">When to Use it</h4>
<p>Use the Bridge pattern when you want to avoid a permanent binding between an abstraction and its implementation, so either can be swapped at runtime.</p>
<p>You can also use it when both the abstraction and the implementation should be independently extensible through subclassing.</p>
<p>And it's a good fit when changes to the implementation should have no impact on the client code. The client shouldn't need to be recompiled.</p>
<h3 id="heading-3-the-composite-design-pattern">3. The Composite Design Pattern</h3>
<h4 id="heading-real-world-example">Real World Example</h4>
<p>Think of a company organisation chart. A company has a CEO. Under the CEO are department heads, each leading a department full of employees. Under some departments are even smaller sub-teams.</p>
<p>Now imagine you want to know the total salary cost. You can ask a single employee they tell you their salary. You can ask a whole department, which adds up every person inside it, including nested teams. Or you can ask the entire company: it rolls up every salary across every level.</p>
<p>The same question, asked the same way, whether you're talking to one person or thousands.</p>
<p>That's the Composite pattern. Individual items and groups of items share the same interface. The caller never needs to know which one they're dealing with.</p>
<h4 id="heading-problems-it-solves">Problems it solves:</h4>
<ul>
<li><p>What if you had to write different code to handle a single employee versus a whole department? You would end up with <code>if</code> checks everywhere just to figure out what you're talking to. Composite removes that entirely: one interface, always.</p>
</li>
<li><p>What if departments can contain other departments? Composite handles any depth of nesting naturally. The caller just asks the top of the tree and the operation flows down automatically.</p>
</li>
<li><p>What if you want to add a new type of team or role? You implement the same interface. Everything above it in the tree keeps working without any changes.</p>
</li>
</ul>
<p>In simple terms, you compose objects into tree structures. This lets individual objects and groups of objects be treated through the same interface, so the caller never has to care about the difference.</p>
<p>Wikipedia describes it like this:</p>
<blockquote>
<p><em>"The composite pattern describes a group of objects that are treated the same way as a single instance of the same type of object. The intent of a composite is to compose objects into tree structures to represent part-whole hierarchies."</em> <a href="https://en.wikipedia.org/wiki/Composite_pattern">(Source</a>)</p>
</blockquote>
<h4 id="heading-programming-example">Programming Example:</h4>
<p>Every node in the tree (whether a single employee or an entire department) implements <code>IEmployee</code>. The caller treats them identically.</p>
<pre><code class="language-csharp">// The component interface — every leaf and composite shares this contract
public interface IEmployee
{
    string Name    { get; }
    int    GetSalary();
    void   GetDetails(string indent = "");
}
</code></pre>
<pre><code class="language-csharp">// The leaf — a single employee with no reports
public class Employee : IEmployee
{
    private readonly int _salary;

    public string Name { get; }

    public Employee(string name, int salary)
    {
        Name    = name;
        _salary = salary;
    }

    public int  GetSalary()                    =&gt; _salary;
    public void GetDetails(string indent = "") =&gt; Console.WriteLine($"{indent}- {Name} (£{_salary:N0})");
}
</code></pre>
<pre><code class="language-csharp">// The composite — a department that holds employees or other departments
public class Department : IEmployee
{
    private readonly List&lt;IEmployee&gt; _members = new();

    public string Name { get; }

    public Department(string name) { Name = name; }

    public void Add(IEmployee employee)    =&gt; _members.Add(employee);
    public void Remove(IEmployee employee) =&gt; _members.Remove(employee);

    public int GetSalary() =&gt; _members.Sum(m =&gt; m.GetSalary());

    public void GetDetails(string indent = "")
    {
        Console.WriteLine($"{indent}[{Name}] Total: £{GetSalary():N0}");
        foreach (var member in _members)
            member.GetDetails(indent + "  ");
    }
}
</code></pre>
<p>Now let's see it in action:</p>
<pre><code class="language-csharp">// Individual employees
var ceo        = new Employee("Alice (CEO)",        120_000);
var cto        = new Employee("Bob (CTO)",           95_000);
var dev1       = new Employee("Carol (Developer)",   65_000);
var dev2       = new Employee("David (Developer)",   62_000);
var cfo        = new Employee("Eve (CFO)",           90_000);
var accountant = new Employee("Frank (Accountant)",  55_000);

// Build the Engineering department
var engineering = new Department("Engineering");
engineering.Add(cto);
engineering.Add(dev1);
engineering.Add(dev2);

// Build the Finance department
var finance = new Department("Finance");
finance.Add(cfo);
finance.Add(accountant);

// Build the whole company
var company = new Department("Acme Corp");
company.Add(ceo);
company.Add(engineering);
company.Add(finance);

// Ask the whole company — one call, rolls up everything
Console.WriteLine("=== Full Company ===");
company.GetDetails();

// Ask just one department — same call, same interface
Console.WriteLine("\n=== Engineering Only ===");
engineering.GetDetails();

// Ask a single employee — same call, same interface
Console.WriteLine("\n=== Single Employee ===");
dev1.GetDetails();
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="language-yaml">=== Full Company ===
[Acme Corp] Total: £487,000
  - Alice (CEO) (£120,000)
  [Engineering] Total: £222,000
    - Bob (CTO) (£95,000)
    - Carol (Developer) (£65,000)
    - David (Developer) (£62,000)
  [Finance] Total: £145,000
    - Eve (CFO) (£90,000)
    - Frank (Accountant) (£55,000)

=== Engineering Only ===
[Engineering] Total: £222,000
  - Bob (CTO) (£95,000)
  - Carol (Developer) (£65,000)
  - David (Developer) (£62,000)

=== Single Employee ===
- Carol (Developer) (£65,000)
</code></pre>
<p><code>company.GetDetails()</code>, <code>engineering.GetDetails()</code>, and <code>dev1.GetDetails()</code>: the same call on three different levels of the tree. The caller never checked what it was talking to. That's the Composite pattern.</p>
<h4 id="heading-when-to-use-it">When to Use it</h4>
<p>Use Composite when you need to represent part-whole hierarchies, like trees where individual items and groups of items need to be used interchangeably.</p>
<p>It also works well when you want client code to treat single objects and collections of objects uniformly, without any special-casing.</p>
<p>And it's a good fit when the structure can be nested to any depth and that depth shouldn't affect how the caller interacts with it.</p>
<h3 id="heading-4-the-decorator-design-pattern">4. The Decorator Design Pattern</h3>
<h4 id="heading-real-world-example">Real World Example</h4>
<p>Think of ordering a coffee at a cafe. You start with a plain espresso. Then you ask for milk. Then vanilla syrup. Then whipped cream on top. Each addition wraps around or adds to what was already there, adding its own cost and its own description. The espresso at the centre never changes. You're just layering on top of it, one addition at a time. You could add two shots of syrup. You could skip the milk entirely. Every combination is possible without creating a new type of coffee for each one.</p>
<p>That's the Decorator pattern. You start with a base object and wrap it in layers. Each layer adds its own behaviour and then delegates to whatever is underneath it.</p>
<h4 id="heading-problems-it-solves">Problems it solves:</h4>
<ul>
<li><p>What if you needed a class for every combination? EspressoWithMilk, EspressoWithMilkAndVanilla, EspressoWithMilkAndVanillaAndCream...the list explodes. Decorator adds behaviour at runtime, so you never need those classes.</p>
</li>
<li><p>What if the base coffee shouldn't change? It does not. The espresso class stays untouched. The decorators wrap around it and extend it independently.</p>
</li>
<li><p>What if a new topping needs to be added? You create one new decorator class. Every existing combination still works exactly as before.</p>
</li>
</ul>
<p>In simple terms, you wrap an object in one or more layers, where each layer adds its own behaviour before or after delegating to the layer beneath it.</p>
<p>Wikipedia describes it like this:</p>
<blockquote>
<p><em>"The decorator pattern is a design pattern that allows behaviour to be added to an individual object, dynamically, without affecting the behaviour of other instances of the same class."</em> <a href="https://en.wikipedia.org/wiki/Decorator_pattern">(Source</a>)</p>
</blockquote>
<h4 id="heading-programming-example">Programming Example:</h4>
<p>The coffee is the component. Each topping is a decorator. Every decorator wraps the component and adds to its description and cost.</p>
<pre><code class="language-csharp">// The component interface — every coffee, plain or decorated, shares this
public interface ICoffee
{
    string GetDescription();
    double GetCost();
}
</code></pre>
<pre><code class="language-csharp">// The base component — a plain espresso
public class Espresso : ICoffee
{
    public string GetDescription() =&gt; "Espresso";
    public double GetCost()        =&gt; 1.00;
}
</code></pre>
<pre><code class="language-csharp">// The base decorator — wraps any ICoffee and delegates to it
public abstract class CoffeeDecorator : ICoffee
{
    protected readonly ICoffee _coffee;

    protected CoffeeDecorator(ICoffee coffee) { _coffee = coffee; }

    public virtual string GetDescription() =&gt; _coffee.GetDescription();
    public virtual double GetCost()        =&gt; _coffee.GetCost();
}
</code></pre>
<pre><code class="language-csharp">// Concrete decorators — each one adds its own layer
public class Milk : CoffeeDecorator
{
    public Milk(ICoffee coffee) : base(coffee) { }

    public override string GetDescription() =&gt; _coffee.GetDescription() + ", Milk";
    public override double GetCost()        =&gt; _coffee.GetCost() + 0.30;
}

public class VanillaSyrup : CoffeeDecorator
{
    public VanillaSyrup(ICoffee coffee) : base(coffee) { }

    public override string GetDescription() =&gt; _coffee.GetDescription() + ", Vanilla Syrup";
    public override double GetCost()        =&gt; _coffee.GetCost() + 0.50;
}

public class WhippedCream : CoffeeDecorator
{
    public WhippedCream(ICoffee coffee) : base(coffee) { }

    public override string GetDescription() =&gt; _coffee.GetDescription() + ", Whipped Cream";
    public override double GetCost()        =&gt; _coffee.GetCost() + 0.75;
}
</code></pre>
<p>Now let's see it in action:</p>
<pre><code class="language-csharp">// A plain espresso
ICoffee order = new Espresso();
Console.WriteLine($"{order.GetDescription()} =&gt; £{order.GetCost():F2}");

// Wrap it with milk
order = new Milk(order);
Console.WriteLine($"{order.GetDescription()} =&gt; £{order.GetCost():F2}");

// Wrap it with vanilla syrup on top
order = new VanillaSyrup(order);
Console.WriteLine($"{order.GetDescription()} =&gt; £{order.GetCost():F2}");

// Wrap it with whipped cream on top of that
order = new WhippedCream(order);
Console.WriteLine($"{order.GetDescription()} =&gt; £{order.GetCost():F2}");
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="language-yaml">Espresso =&gt; £1.00
Espresso, Milk =&gt; £1.30
Espresso, Milk, Vanilla Syrup =&gt; £1.80
Espresso, Milk, Vanilla Syrup, Whipped Cream =&gt; £2.55
</code></pre>
<p>Each line is a new layer wrapped around the previous one. The espresso never changed. The cost and description grew with every wrapper. That's the Decorator pattern.</p>
<h4 id="heading-when-to-use-it">When to Use it</h4>
<p>Use the Decorator pattern when you want to add responsibilities to individual objects without affecting other objects of the same class.</p>
<p>It's also a good choice when subclassing would lead to an explosion of classes to cover every possible combination of behaviours.</p>
<p>And use it when you need to be able to stack behaviours in any order at runtime, independently of each other.</p>
<h3 id="heading-5-the-facade-design-pattern">5. The Facade Design Pattern</h3>
<h4 id="heading-real-world-example">Real World Example</h4>
<p>Think of clicking "Place Order" on a shopping website. In that single click, several things happen behind the scenes: the system checks whether the item is in stock, your payment is charged, a shipping label is generated, and a confirmation email is sent to you. You don't see any of that. You click one button and get one result. The complexity of four separate systems is hidden behind a single, clean action.</p>
<p>That's the Facade pattern: one simple interface in front of many complex moving parts. The caller doesn't need to know what's happening behind the scenes.</p>
<h4 id="heading-problems-it-solves">Problems it solves:</h4>
<ul>
<li><p>What if the client had to call each subsystem directly? Check inventory, then process payment, then generate a label, and then send an email, all in the right order, handling each failure separately. The Facade wraps all of that into one call.</p>
</li>
<li><p>What if one of the subsystems changes? The Facade absorbs the change. The client code never needs to know. Only the Facade is updated.</p>
</li>
<li><p>What if different clients need the same flow? They all call the same Facade method. The logic is in one place, not duplicated across every caller.</p>
</li>
</ul>
<p>In simple terms, you provide a single, simple interface that hides the complexity of a set of subsystems behind it.</p>
<p>Wikipedia describes it like this:</p>
<blockquote>
<p><em>"The facade pattern (also spelled façade) is a software-design pattern commonly used in object-oriented programming. Analogous to a facade in architecture, a facade is an object that serves as a front-facing interface masking more complex underlying or structural code."</em><a href="https://en.wikipedia.org/wiki/Facade_pattern">(Source</a>)</p>
</blockquote>
<h4 id="heading-programming-example">Programming Example:</h4>
<p>Each subsystem does its own job. The <code>OrderFacade</code> is the single entry point that coordinates all of them. The client only ever talks to the facade.</p>
<pre><code class="language-csharp">// Subsystem 1: checks whether the item is available
public class InventoryService
{
    public bool CheckStock(string item)
    {
        Console.WriteLine($"Inventory: Checking stock for {item}.");
        return true;
    }
}
</code></pre>
<pre><code class="language-csharp">// Subsystem 2: handles the payment
public class PaymentService
{
    public bool ProcessPayment(string cardNumber, double amount)
    {
        Console.WriteLine($"Payment: Charging £{amount:F2} to card ending {cardNumber[^4..]}.");
        return true;
    }
}
</code></pre>
<pre><code class="language-csharp">// Subsystem 3: generates a shipping label
public class ShippingService
{
    public string GenerateLabel(string item, string address)
    {
        Console.WriteLine($"Shipping: Generating label for {item} to {address}.");
        return "TRACK-29384";
    }
}
</code></pre>
<pre><code class="language-csharp">// Subsystem 4: sends the confirmation email
public class EmailService
{
    public void SendConfirmation(string email, string trackingCode)
    {
        Console.WriteLine($"Email: Confirmation sent to {email}. Tracking code: {trackingCode}.");
    }
}
</code></pre>
<pre><code class="language-csharp">// The Facade — one method, hides all four subsystems
public class OrderFacade
{
    private readonly InventoryService _inventory = new();
    private readonly PaymentService   _payment   = new();
    private readonly ShippingService  _shipping  = new();
    private readonly EmailService     _email     = new();

    public void PlaceOrder(string item, string cardNumber, double amount, string address, string email)
    {
        Console.WriteLine("=== Placing Order ===");

        if (!_inventory.CheckStock(item))
        {
            Console.WriteLine("Order failed: item out of stock.");
            return;
        }

        if (!_payment.ProcessPayment(cardNumber, amount))
        {
            Console.WriteLine("Order failed: payment declined.");
            return;
        }

        string trackingCode = _shipping.GenerateLabel(item, address);
        _email.SendConfirmation(email, trackingCode);

        Console.WriteLine($"\nOrder complete. Your tracking code is {trackingCode}.");
    }
}
</code></pre>
<p>Now let's see it in action:</p>
<pre><code class="language-csharp">OrderFacade store = new OrderFacade();

store.PlaceOrder(
    item:       "Wireless Headphones",
    cardNumber: "4111111111111234",
    amount:     79.99,
    address:    "42 Maple Street, London",
    email:      "customer@email.com"
);
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="language-yaml">=== Placing Order ===
Inventory: Checking stock for Wireless Headphones.
Payment: Charging £79.99 to card ending 1234.
Shipping: Generating label for Wireless Headphones to 42 Maple Street, London.
Email: Confirmation sent to customer@email.com. Tracking code: TRACK-29384.

Order complete. Your tracking code is TRACK-29384.
</code></pre>
<blockquote>
<p>The client called one method. Four subsystems ran in the right order. None of that complexity was visible to the caller. That is the Facade.</p>
</blockquote>
<h4 id="heading-when-to-use-it">When to Use it</h4>
<p>Use Facade when you want to provide a simple interface to a complex subsystem so callers aren't burdened by its internals.</p>
<p>It also works well when you want to layer your system so that high-level code talks to facades, not directly to low-level subsystems.</p>
<p>And it's a good choice when you want a single entry point that coordinates a sequence of steps across multiple services.</p>
<h3 id="heading-6-the-flyweight-design-pattern">6. The Flyweight Design Pattern</h3>
<h4 id="heading-real-world-example">Real World Example</h4>
<p>Think of a game that renders a forest. The forest has ten thousand trees. Each tree has a type name, a colour, and a texture. But most of those trees are Oaks, and all Oaks look exactly the same.</p>
<p>Creating ten thousand separate objects, each storing the same name, colour, and texture, wastes enormous amounts of memory. Instead, you create one shared Oak object that holds all that data. Every Oak tree in the forest points to that same shared object and only stores its own position on the map.</p>
<p>That's the Flyweight pattern. The data that's the same across many instances is shared. The data that's unique per instance is stored separately and passed in only when needed.</p>
<h4 id="heading-problems-it-solves">Problems it solves:</h4>
<ul>
<li><p>What if you created a full object for every single tree? With ten thousand trees, you store the same name, colour, and texture ten thousand times. Flyweight stores that shared data once and reuses it everywhere.</p>
</li>
<li><p>What if a new tree type is introduced? The factory creates one new shared object for it. Every tree of that type immediately uses it without any extra memory.</p>
</li>
<li><p>What if the forest needs to render each tree at its own position? The position is unique per tree, so it's stored on the tree itself and passed to the shared object only at render time. The shared object never holds it.</p>
</li>
</ul>
<p>In simple terms, you split an object's data into what's shared across many instances and what's unique per instance. Share the common part. Pass the unique part in only when needed.</p>
<p>Wikipedia describes it like this:</p>
<blockquote>
<p><em>"A flyweight is an object that minimizes memory usage by sharing as much data as possible with other similar objects. It is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory."</em> <a href="https://en.wikipedia.org/wiki/Flyweight_pattern">(Source</a>)</p>
</blockquote>
<h4 id="heading-programming-examplel">Programming ExampleL</h4>
<p><code>TreeType</code> is the flyweight: it holds shared data. <code>Tree</code> holds only the unique position and a reference to a shared <code>TreeType</code>. The factory ensures each <code>TreeType</code> is created only once.</p>
<pre><code class="language-csharp">// The flyweight — holds shared intrinsic state (same for all trees of this type)
public class TreeType
{
    public string Name    { get; }
    public string Colour  { get; }
    public string Texture { get; }

    public TreeType(string name, string colour, string texture)
    {
        Name    = name;
        Colour  = colour;
        Texture = texture;
    }

    public void Render(int x, int y)
    {
        Console.WriteLine($"Rendering {Name} tree ({Colour}, {Texture}) at ({x}, {y})");
    }
}
</code></pre>
<pre><code class="language-csharp">// The flyweight factory — creates and caches tree types so they are never duplicated
public class TreeTypeFactory
{
    private readonly Dictionary&lt;string, TreeType&gt; _cache = new();

    public TreeType GetTreeType(string name, string colour, string texture)
    {
        string key = $"{name}_{colour}_{texture}";

        if (!_cache.ContainsKey(key))
        {
            Console.WriteLine($"Factory: Creating new TreeType for '{name}'.");
            _cache[key] = new TreeType(name, colour, texture);
        }

        return _cache[key];
    }

    public int TotalTypes =&gt; _cache.Count;
}
</code></pre>
<pre><code class="language-csharp">// The context — holds unique extrinsic state (position) and a reference to a shared flyweight
public class Tree
{
    private readonly int      _x;
    private readonly int      _y;
    private readonly TreeType _type;

    public Tree(int x, int y, TreeType type)
    {
        _x    = x;
        _y    = y;
        _type = type;
    }

    public void Render() =&gt; _type.Render(_x, _y);
}
</code></pre>
<pre><code class="language-csharp">// The forest — plants trees using shared flyweights
public class Forest
{
    private readonly List&lt;Tree&gt;      _trees   = new();
    private readonly TreeTypeFactory _factory = new();

    public void PlantTree(int x, int y, string name, string colour, string texture)
    {
        TreeType type = _factory.GetTreeType(name, colour, texture);
        _trees.Add(new Tree(x, y, type));
    }

    public void Render()
    {
        foreach (var tree in _trees)
            tree.Render();
    }

    public int TreeCount     =&gt; _trees.Count;
    public int TreeTypeCount =&gt; _factory.TotalTypes;
}
</code></pre>
<p>Now let's see it in action:</p>
<pre><code class="language-csharp">Forest forest = new Forest();

// Plant 6 trees — but only 2 unique types
forest.PlantTree(1,  5,  "Oak",  "Dark Green",  "Rough bark");
forest.PlantTree(3,  12, "Oak",  "Dark Green",  "Rough bark");
forest.PlantTree(7,  2,  "Oak",  "Dark Green",  "Rough bark");
forest.PlantTree(10, 8,  "Pine", "Light Green", "Smooth bark");
forest.PlantTree(15, 3,  "Pine", "Light Green", "Smooth bark");
forest.PlantTree(20, 14, "Pine", "Light Green", "Smooth bark");

forest.Render();

Console.WriteLine($"\nTrees planted:              {forest.TreeCount}");
Console.WriteLine($"Unique tree types in memory: {forest.TreeTypeCount}");
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="language-plaintext">Factory: Creating new TreeType for 'Oak'.
Factory: Creating new TreeType for 'Pine'.
Rendering Oak tree (Dark Green, Rough bark) at (1, 5)
Rendering Oak tree (Dark Green, Rough bark) at (3, 12)
Rendering Oak tree (Dark Green, Rough bark) at (7, 2)
Rendering Pine tree (Light Green, Smooth bark) at (10, 8)
Rendering Pine tree (Light Green, Smooth bark) at (15, 3)
Rendering Pine tree (Light Green, Smooth bark) at (20, 14)

Trees planted:              6
Unique tree types in memory: 2
</code></pre>
<p>Six trees, but only two <code>TreeType</code> objects were ever created. Scale that to ten thousand trees and the factory still creates exactly two. The positions are unique per tree, and the appearance is shared. That's the Flyweight.</p>
<h4 id="heading-when-to-use-it">When to Use it</h4>
<p>Use Flyweight when your application needs to create a very large number of similar objects that would otherwise consume too much memory.</p>
<p>It's also useful when most of the object's state can be made shared across instances, with only a small part being unique per instance.</p>
<p>And it's a good choice when the unique part of the state can be passed in externally rather than stored inside every object.</p>
<h3 id="heading-7-the-proxy-design-pattern">7. The Proxy Design Pattern</h3>
<h4 id="heading-real-world-example">Real World Example</h4>
<p>Think of a security guard at the entrance of an office building. You can't walk straight into the building. You have to go through the guard first. The guard checks your name against the authorised list, logs your visit, and only then lets you through. If you're not on the list, you're turned away. The building itself never deals with any of that. It just lets people in. All the checking, logging, and decision-making happens at the guard (the proxy) before the building ever gets involved.</p>
<p>That's the Proxy pattern. It sits between the caller and the real object, controls what gets through, and can add behaviour like access checks or logging without the real object knowing anything about it.</p>
<h4 id="heading-problems-it-solves">Problems it solves:</h4>
<ul>
<li><p>What if anyone could walk straight into the building? There would be no access control. The proxy intercepts every request and decides whether it should be allowed through.</p>
</li>
<li><p>What if you need to log every entry without changing the building? The proxy handles it. The real building stays simple and focused on its own job.</p>
</li>
<li><p>What if the real object is expensive to create and you want to delay that? The proxy can hold off creating it until someone actually passes the check and needs it.</p>
</li>
</ul>
<p>In simple terms, you place an object in front of another object to control access to it. The caller thinks it's talking directly to the real object, but the proxy is handling it first.</p>
<p>Wikipedia describes it like this:</p>
<blockquote>
<p><em>"A proxy, in its most general form, is a class functioning as an interface to something else. The proxy could interface to anything: a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate." (</em><a href="https://en.wikipedia.org/wiki/Proxy_pattern">Source</a>)</p>
</blockquote>
<h4 id="heading-programming-example">Programming Example:</h4>
<p>The client talks to <code>IBuilding</code>. The <code>SecurityGuard</code> is the proxy: it implements the same interface, controls access, and only lets authorised visitors through to the <code>OfficeBuilding</code>.</p>
<pre><code class="language-csharp">// The subject interface — the building and the proxy both implement this
public interface IBuilding
{
    void Enter(string visitorName);
}
</code></pre>
<pre><code class="language-csharp">// The real subject — the actual building, just grants entry
public class OfficeBuilding : IBuilding
{
    public void Enter(string visitorName)
    {
        Console.WriteLine($"Building: {visitorName} has entered.");
    }
}
</code></pre>
<pre><code class="language-csharp">// The proxy — the security guard controls who gets through
public class SecurityGuard : IBuilding
{
    private readonly OfficeBuilding _building          = new();
    private readonly List&lt;string&gt;   _authorisedVisitors = new() { "Alice", "Bob", "Carol" };

    public void Enter(string visitorName)
    {
        Console.WriteLine($"Guard: {visitorName} is requesting entry.");

        if (_authorisedVisitors.Contains(visitorName))
        {
            Console.WriteLine("Guard: ID verified. Access granted.");
            _building.Enter(visitorName);
        }
        else
        {
            Console.WriteLine($"Guard: {visitorName} is not on the list. Access denied.");
        }
    }
}
</code></pre>
<p>Now let's see it in action:</p>
<pre><code class="language-csharp">IBuilding entrance = new SecurityGuard();

entrance.Enter("Alice");
Console.WriteLine();
entrance.Enter("David");
Console.WriteLine();
entrance.Enter("Bob");
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="language-yaml">Guard: Alice is requesting entry.
Guard: ID verified. Access granted.
Building: Alice has entered.

Guard: David is requesting entry.
Guard: David is not on the list. Access denied.

Guard: Bob is requesting entry.
Guard: ID verified. Access granted.
Building: Bob has entered.
</code></pre>
<p>The client called <code>Enter()</code> on what it thought was the building. It was actually the security guard. The guard decided what happened. The building only ever saw the people who were allowed through. That's the Proxy.</p>
<h4 id="heading-when-to-use-it">When to Use it</h4>
<p>Use Proxy when you need access control, like only letting certain callers through to the real object.</p>
<p>It's a good fit when you want to add behaviour such as logging, caching, or validation without changing the real object.</p>
<p>And you can use it when the real object is expensive to create and you want to delay or guard that creation until it's truly needed.</p>
<h2 id="heading-behavioral-design-patterns">Behavioral Design Patterns</h2>
<p>Simply put, behavioral patterns are all about <strong>how objects communicate and share responsibility</strong>. They focus on the assignment of responsibilities between objects, and how objects cooperate to get a job done.</p>
<p>Wikipedia describes them as:</p>
<blockquote>
<p><em>"In software engineering, behavioral design patterns are design patterns that identify common communication patterns among objects. By doing so, these patterns increase flexibility in carrying out this communication." (</em><a href="https://en.wikipedia.org/wiki/Behavioral_pattern">Source</a>)</p>
</blockquote>
<p>Behavioral design patterns describe how objects interact and distribute responsibility, not just how they're structured. They focus on communication between objects: who talks to whom, and how much each side knows about the other.</p>
<p>There are 11 behavioral design patterns:</p>
<ol>
<li><p><strong>Chain of Responsibility</strong>: Passes a request along a chain of handlers, letting each one decide to handle it or pass it on.</p>
</li>
<li><p><strong>Command</strong>: Encapsulates a request as an object, letting you parameterize clients, queue actions, and support undo.</p>
</li>
<li><p><strong>Interpreter</strong>: Given a language, defines a representation for its grammar along with an interpreter that evaluates sentences in it.</p>
</li>
<li><p><strong>Iterator</strong>: Provides a way to access the elements of a collection sequentially without exposing how it's built underneath.</p>
</li>
<li><p><strong>Mediator</strong>: Defines an object that encapsulates how a set of objects interact, so they don't refer to each other directly.</p>
</li>
<li><p><strong>Memento</strong>: Captures an object's internal state so it can be restored later, without breaking encapsulation.</p>
</li>
<li><p><strong>Observer</strong>: Defines a one-to-many dependency so that when one object changes state, everything depending on it is notified automatically.</p>
</li>
<li><p><strong>State</strong>: Lets an object change its behaviour when its internal state changes, as if it had changed its class.</p>
</li>
<li><p><strong>Strategy</strong>: Defines a family of interchangeable algorithms and lets the client pick which one to use at runtime.</p>
</li>
<li><p><strong>Template Method</strong>: Defines the skeleton of an algorithm in a method, leaving some steps for subclasses to fill in.</p>
</li>
<li><p><strong>Visitor</strong>: Lets you define a new operation without changing the classes of the elements it operates on.</p>
</li>
</ol>
<h3 id="heading-1-the-chain-of-responsibility-design-pattern">1. The Chain of Responsibility Design Pattern</h3>
<h4 id="heading-real-world-example">Real World Example</h4>
<p>Think of an expense approval process at a company. An employee submits a request to their director. If the amount is small enough, the director approves it and that's the end of it. If it's too large for the director to sign off on, it goes up to the vice president. If it's still too large, it goes up to the chief executive.</p>
<p>Each person in the chain only needs to know two things: what they're allowed to approve, and who to hand it to if they can't. The employee never needs to know who ends up approving it.</p>
<p>That's the Chain of Responsibility design pattern. A request travels along a chain of handlers until one of them deals with it, and each handler only cares about its own link in that chain.</p>
<h4 id="heading-problems-it-solves">Problems it solves:</h4>
<ul>
<li><p>What if the sender had to know exactly who should handle the request? That would tie the sender to a specific handler and break the moment the approval structure changed. The chain lets the sender submit the request without knowing who will end up handling it.</p>
</li>
<li><p>What if one handler could only ever approve or reject, with no fallback? Requests that fell outside its authority would simply fail. The chain lets a handler pass what it can't deal with further along.</p>
</li>
<li><p>What if you needed to change the approval structure? Rewiring which handler comes after which is enough. Neither the sender nor the other handlers need to change.</p>
</li>
</ul>
<p>In simple terms, you pass a request along a chain of handlers. Each handler decides whether to deal with it or hand it off to the next one in line.</p>
<p>Wikipedia describes it like this:</p>
<blockquote>
<p><em>"In object-oriented design, the chain-of-responsibility pattern is a behavioral design pattern consisting of a source of command objects and a series of processing objects. Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain."</em></p>
<p><strong>(</strong><a href="https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern">Source</a>)</p>
</blockquote>
<h4 id="heading-programming-example">Programming Example:</h4>
<p>Each <code>Approver</code> knows its own approval limit and holds a reference to the next approver in the chain. The <code>ExpenseRequest</code> is passed along until someone can approve it, or nobody can.</p>
<pre><code class="language-csharp">// The request that travels along the chain
public class ExpenseRequest
{
    public string Description { get; }
    public decimal Amount     { get; }

    public ExpenseRequest(string description, decimal amount)
    {
        Description = description;
        Amount      = amount;
    }
}
</code></pre>
<pre><code class="language-csharp">// The handler, every link in the chain implements this
public abstract class Approver
{
    private Approver? _next;

    public void SetNext(Approver next) =&gt; _next = next;

    public void Approve(ExpenseRequest request)
    {
        if (CanApprove(request))
        {
            Console.WriteLine($"{GetType().Name}: Approved '{request.Description}' (${request.Amount}).");
        }
        else if (_next is not null)
        {
            Console.WriteLine($"{GetType().Name}: Can't approve '{request.Description}' (${request.Amount}). Passing it up.");
            _next.Approve(request);
        }
        else
        {
            Console.WriteLine($"{GetType().Name}: No one left to approve '{request.Description}' (${request.Amount}). Request denied.");
        }
    }

    protected abstract bool CanApprove(ExpenseRequest request);
}
</code></pre>
<pre><code class="language-csharp">// Concrete handlers, each with its own approval limit
public class Director : Approver
{
    protected override bool CanApprove(ExpenseRequest request) =&gt; request.Amount &lt;= 1000;
}

public class VicePresident : Approver
{
    protected override bool CanApprove(ExpenseRequest request) =&gt; request.Amount &lt;= 20000;
}

public class Chief : Approver
{
    protected override bool CanApprove(ExpenseRequest request) =&gt; request.Amount &lt;= 50000;
}
</code></pre>
<p>Now let's see it in action:</p>
<pre><code class="language-csharp">Approver directorApprover = new Director();
Approver vpApprover       = new VicePresident();
Approver ceoApprover      = new Chief();

directorApprover.SetNext(vpApprover);
vpApprover.SetNext(ceoApprover);

directorApprover.Approve(new ExpenseRequest("Laptop", 800));
Console.WriteLine();
directorApprover.Approve(new ExpenseRequest("Team offsite", 12000));
Console.WriteLine();
directorApprover.Approve(new ExpenseRequest("New office lease", 90000));
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="language-yaml">Director: Approved 'Laptop' ($800).

Director: Can't approve 'Team offsite' ($12000). Passing it up.
VicePresident: Approved 'Team offsite' ($12000).

Director: Can't approve 'New office lease' ($90000). Passing it up.
VicePresident: Can't approve 'New office lease' ($90000). Passing it up.
Chief: No one left to approve 'New office lease' ($90000). Request denied.
</code></pre>
<p>The employee only ever talked to the director. Whether the director, the vice president, or the chief ended up approving it, was decided by the chain itself, not the employee.</p>
<h4 id="heading-when-to-use-it">When to Use it</h4>
<p>Use Chain of Responsibility when more than one object might handle a request, and the handler isn't known in advance.</p>
<p>It's also a good choice when you want to issue a request without specifying the receiver explicitly.</p>
<p>And it's helpful when the set of handlers, and their order, should be configurable rather than hard-coded.</p>
<h3 id="heading-2-the-command-design-pattern">2. The Command Design Pattern</h3>
<h4 id="heading-real-world-example">Real World Example</h4>
<p>Think of a universal remote control. Every button is programmed to do one specific thing: turn a light on, turn a light off, and so on. When you press a button, the remote doesn't know or care how the light actually works internally. It just triggers the action that button was set up to perform. And because each button's action is a self-contained thing, the remote can also press it in reverse, undoing what it just did.</p>
<p>That's the Command pattern. A request "turn the light on" is wrapped up as its own object. The thing that triggers it doesn't need to know anything about how it's carried out.</p>
<h4 id="heading-problems-it-solves">Problems it solves:</h4>
<ul>
<li><p>What if the button had to know exactly how the light worked? Every button would need to be rewritten if the light's internals changed. Wrapping the action as a command means the remote never touches those details.</p>
</li>
<li><p>What if you wanted to undo the last action? Without a command object there's nothing to reverse, only a completed side effect. Wrapping the action gives you something you can also unwind.</p>
</li>
<li><p>What if you wanted to queue actions, log them, or trigger them later? A plain method call happens immediately and leaves nothing behind. A command is an object, so it can be stored, queued, and replayed.</p>
</li>
</ul>
<p>In simple terms, you wrap a request up as an object, so the thing that triggers it doesn't need to know how it's carried out, and the action itself can be queued, logged, or undone.</p>
<p>Wikipedia describes it like this:</p>
<blockquote>
<p><em>"The command pattern is a behavioral design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time." (</em><a href="https://en.wikipedia.org/wiki/Command_pattern">Source</a>)</p>
</blockquote>
<h4 id="heading-programming-example">Programming Example:</h4>
<p>The <code>RemoteControl</code> is the invoker it only knows about <code>ICommand</code>. <code>LightOnCommand</code> and <code>LightOffCommand</code> are the concrete commands, each wrapping the <code>Light</code> receiver and the action to perform on it.</p>
<pre><code class="language-csharp">// The command interface, every action implements this
public interface ICommand
{
    void Execute();
    void Undo();
}
</code></pre>
<pre><code class="language-csharp">// The receiver, the object that actually does the work
public class Light
{
    private readonly string _room;

    public Light(string room) =&gt; _room = room;

    public void On()  =&gt; Console.WriteLine($"{_room} light: turned on.");
    public void Off() =&gt; Console.WriteLine($"{_room} light: turned off.");
}
</code></pre>
<pre><code class="language-csharp">// Concrete commands, each wraps a receiver and an action
public class LightOnCommand : ICommand
{
    private readonly Light _light;

    public LightOnCommand(Light light) =&gt; _light = light;

    public void Execute() =&gt; _light.On();
    public void Undo()    =&gt; _light.Off();
}

public class LightOffCommand : ICommand
{
    private readonly Light _light;

    public LightOffCommand(Light light) =&gt; _light = light;

    public void Execute() =&gt; _light.Off();
    public void Undo()    =&gt; _light.On();
}
</code></pre>
<pre><code class="language-csharp">// The invoker, it holds a command and triggers it without knowing what it does
public class RemoteControl
{
    private ICommand? _command;

    public void SetCommand(ICommand command) =&gt; _command = command;

    public void PressButton() =&gt; _command?.Execute();
    public void PressUndo()   =&gt; _command?.Undo();
}
</code></pre>
<p>Now let's see it in action:</p>
<pre><code class="language-csharp">var livingRoomLight = new Light("Living Room");
var remote          = new RemoteControl();

remote.SetCommand(new LightOnCommand(livingRoomLight));
remote.PressButton();

remote.SetCommand(new LightOffCommand(livingRoomLight));
remote.PressButton();

Console.WriteLine();
Console.WriteLine("Undoing last action...");
remote.PressUndo();
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="language-yaml">Living Room light: turned on.
Living Room light: turned off.

Undoing last action...
Living Room light: turned on.
</code></pre>
<p>The remote never called <code>_light.On()</code> or <code>_light.Off()</code> directly. It called <code>Execute()</code> and <code>Undo()</code> on whatever command it was holding. That's the Command pattern: the request itself became an object.</p>
<h4 id="heading-when-to-use-it">When to Use it</h4>
<p>Use the Command pattern when you want to parameterize objects with an action to perform, rather than hard-coding it.</p>
<p>Reach for it when you need to queue, log, or support undo for requests.</p>
<p>And consider it when you want to decouple the object that invokes an action from the object that knows how to perform it.</p>
<h3 id="heading-3-the-interpreter-design-pattern">3. The Interpreter Design Pattern</h3>
<h4 id="heading-real-world-example">Real World Example</h4>
<p>Think of a basic calculator reading an expression like <code>(5 + 3) - 2</code>. Nobody hardcodes a single method that handles every possible expression. Instead, the expression is broken down into small pieces: numbers and operation buttons, each of which knows how to evaluate itself and combine with the others. <code>(5 + 3) - 2</code> becomes a subtraction of two things: the number 2, and the result of adding 5 and 3. Each piece only needs to know how to interpret itself.</p>
<p>That's the Interpreter pattern. A grammar is represented as a tree of small objects, and each one knows how to evaluate its own little piece of it.</p>
<h4 id="heading-problems-it-solves">Problems it solves:</h4>
<ul>
<li><p>What if you tried to evaluate an entire expression in one big method? It would grow unmanageable the moment the grammar got more complex. Breaking the grammar into small classes, one per rule, keeps each piece simple.</p>
</li>
<li><p>What if the grammar needed to grow? Adding a new operation, like multiplication, is just a new class. The existing pieces don't need to change.</p>
</li>
<li><p>What if the same expression needed to be evaluated more than once, or in different contexts? Because each piece is just an object, the same tree can be interpreted again without rebuilding it.</p>
</li>
</ul>
<p>In simple terms, you represent a grammar as a tree of small objects, where each object knows how to interpret its own piece of the expression.</p>
<p>Wikipedia describes it like this:</p>
<blockquote>
<p><em>"In computer programming, the interpreter pattern is a design pattern that specifies how to evaluate sentences in a language. The basic idea is to have a class for each symbol (terminal or nonterminal) in a specialized computer language." (</em><a href="https://en.wikipedia.org/wiki/Interpreter_pattern">Source</a>)</p>
</blockquote>
<h4 id="heading-programming-example">Programming Example:</h4>
<p><code>Number</code> is the terminal expression, a plain value. <code>Add</code> and <code>Subtract</code> are non-terminal expressions, each combining two other expressions. Every node, terminal or not, knows how to <code>Interpret()</code> itself.</p>
<pre><code class="language-csharp">// The abstract expression, every node in the grammar implements this
public abstract class Expression
{
    public abstract int Interpret();
}
</code></pre>
<pre><code class="language-csharp">// A terminal expression, a plain number that needs no further interpretation
public class Number : Expression
{
    private readonly int _value;

    public Number(int value) =&gt; _value = value;

    public override int Interpret() =&gt; _value;
}
</code></pre>
<pre><code class="language-csharp">// Non-terminal expressions, each combines other expressions
public class Add : Expression
{
    private readonly Expression _left;
    private readonly Expression _right;

    public Add(Expression left, Expression right)
    {
        _left  = left;
        _right = right;
    }

    public override int Interpret() =&gt; _left.Interpret() + _right.Interpret();
}

public class Subtract : Expression
{
    private readonly Expression _left;
    private readonly Expression _right;

    public Subtract(Expression left, Expression right)
    {
        _left  = left;
        _right = right;
    }

    public override int Interpret() =&gt; _left.Interpret() - _right.Interpret();
}
</code></pre>
<p>Now let's see it in action:</p>
<pre><code class="language-csharp">// (5 plus 3) minus 2
Expression expression = new Subtract(
    new Add(new Number(5), new Number(3)),
    new Number(2)
);

Console.WriteLine($"Result: {expression.Interpret()}");

// (10 minus 4) plus (2 plus 2)
Expression another = new Add(
    new Subtract(new Number(10), new Number(4)),
    new Add(new Number(2), new Number(2))
);

Console.WriteLine($"Result: {another.Interpret()}");
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="language-yaml">Result: 6
Result: 10
</code></pre>
<p>Nothing ever evaluated the whole expression at once. <code>Subtract</code> asked its own <code>_left</code> and <code>_right</code> to interpret themselves, and those asked their own children, all the way down to plain numbers. That's the Interpreter pattern: the grammar interprets itself, one small piece at a time.</p>
<h4 id="heading-when-to-use-it">When to Use it</h4>
<p>Use Interpreter when you have a simple language or grammar to evaluate, and representing it as a tree of expressions keeps it manageable.</p>
<p>It also works well when the grammar is relatively stable. For example, adding new rules means adding new classes, not rewriting existing ones.</p>
<p>And it's useful when you would rather have many small, focused classes than one large method trying to parse and evaluate everything at once.</p>
<h3 id="heading-4-the-iterator-design-pattern">4. The Iterator Design Pattern</h3>
<h4 id="heading-real-world-example">Real World Example</h4>
<p>Think of a bookshelf. You want to go through it one book at a time, from left to right, without needing to know whether the books are held in an array, multiple piles and stacks, or something else entirely. All you need is a way to ask "what's next?" and to know when you've reached the end. How the shelf actually stores its books internally is none of your concern.</p>
<p>That's the Iterator pattern. It gives you a consistent way to step through a collection, one element at a time, without exposing how that collection is built underneath.</p>
<h4 id="heading-problems-it-solves">Problems it solves:</h4>
<ul>
<li><p>What if the client had to know how the collection was stored internally to loop over it? Any change to that internal structure would break every piece of code that loops over it. The iterator hides that structure behind a simple "get next" interface.</p>
</li>
<li><p>What if you needed more than one traversal in progress at the same time? A single shared position wouldn't work. Each iterator keeps its own position, so multiple traversals can happen independently.</p>
</li>
<li><p>What if you wanted to loop over the collection using the language's own <code>foreach</code>? Implementing the iterator interface the language expects means your custom collection gets that support for free.</p>
</li>
</ul>
<p>In simple terms, you give a collection a way to be walked through, one element at a time, without exposing how it's actually built underneath.</p>
<p>Wikipedia describes it like this:</p>
<blockquote>
<p><em>"In object-oriented programming, the iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container's elements."</em> <a href="https://en.wikipedia.org/wiki/Iterator_pattern">(Source</a>)</p>
</blockquote>
<h4 id="heading-programming-example">Programming Example:</h4>
<p><code>Bookshelf</code> is the aggregate it exposes an <code>IEnumerator&lt;string&gt;</code> without revealing that it stores books in a <code>List&lt;string&gt;</code> internally. <code>BookshelfIterator</code> is the iterator that walks through them one at a time.</p>
<pre><code class="language-csharp">// The aggregate, exposes an iterator without revealing how books are stored
public class Bookshelf : IEnumerable&lt;string&gt;
{
    private readonly List&lt;string&gt; _books = new();

    public void Add(string title) =&gt; _books.Add(title);

    public IEnumerator&lt;string&gt; GetEnumerator() =&gt; new BookshelfIterator(_books);

    IEnumerator IEnumerable.GetEnumerator() =&gt; GetEnumerator();
}
</code></pre>
<pre><code class="language-csharp">// The iterator, walks the collection one book at a time
public class BookshelfIterator : IEnumerator&lt;string&gt;
{
    private readonly List&lt;string&gt; _books;
    private int _position = -1;

    public BookshelfIterator(List&lt;string&gt; books) =&gt; _books = books;

    public string Current =&gt; _books[_position];

    object IEnumerator.Current =&gt; Current;

    public bool MoveNext()
    {
        _position++;
        return _position &lt; _books.Count;
    }

    public void Reset() =&gt; _position = -1;

    public void Dispose() { }
}
</code></pre>
<p>Now let's see it in action:</p>
<pre><code class="language-csharp">var bookshelf = new Bookshelf();
bookshelf.Add("Clean Code");
bookshelf.Add("The Pragmatic Programmer");
bookshelf.Add("Design Patterns");

foreach (var book in bookshelf)
{
    Console.WriteLine($"On the shelf: {book}");
}
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="language-yaml">On the shelf: Clean Code
On the shelf: The Pragmatic Programmer
On the shelf: Design Patterns
</code></pre>
<p>The <code>foreach</code> loop never touched the <code>List&lt;string&gt;</code> inside <code>Bookshelf</code> directly. It called <code>MoveNext()</code> and <code>Current</code> on the <code>BookshelfIterator</code>, one step at a time. That's the Iterator pattern: the traversal logic lives outside the collection itself.</p>
<h4 id="heading-when-to-use-it">When to Use it</h4>
<p>Use Iterator when you want to traverse a collection without exposing its internal structure.</p>
<p>It's also a good choice when you need to support multiple simultaneous traversals over the same collection.</p>
<p>And try it when you want your custom collection to work with the language's built-in iteration syntax, like <code>foreach</code>.</p>
<h3 id="heading-5-the-mediator-design-pattern">5. The Mediator Design Pattern</h3>
<h4 id="heading-real-world-example">Real World Example</h4>
<p>Think of an air traffic control tower. Planes don't radio each other directly to negotiate who lands first. That would be chaos: dozens of pilots all trying to coordinate with each other at once.</p>
<p>Instead, every plane talks only to the tower. The tower knows the state of the runway and tells each plane what to do. The planes never need to know how many other planes are around, or what they're doing.</p>
<p>That's the Mediator pattern. Instead of objects talking to each other directly, they all talk to one central object that coordinates them.</p>
<h4 id="heading-problems-it-solves">Problems it solves:</h4>
<ul>
<li><p>What if every aircraft had to communicate directly with every other aircraft? The number of connections would explode as more aircraft joined, and each one would need to know about all the others. The mediator means each aircraft only needs to know about the tower.</p>
</li>
<li><p>What if the coordination logic was scattered across every object involved? Changing how landings get prioritised would mean touching every aircraft. With a mediator, that logic lives in one place.</p>
</li>
<li><p>What if you wanted to add a new aircraft to the system? It only needs to know how to talk to the tower. It doesn't need to be introduced to every other aircraft already in the sky.</p>
</li>
</ul>
<p>In simple terms, instead of letting objects talk to each other directly, you route all communication through one central object that knows how to coordinate them.</p>
<p>Wikipedia describes it like this:</p>
<blockquote>
<p><em>"In software engineering, the mediator pattern defines an object that encapsulates how a set of objects interact. This pattern is considered to be a behavioral pattern due to the way it can alter the program's running behavior." (</em><a href="https://en.wikipedia.org/wiki/Mediator_pattern">Source</a>)</p>
</blockquote>
<h4 id="heading-programming-example">Programming Example:</h4>
<p><code>ControlTower</code> is the mediator. It's the only thing an <code>Aircraft</code> ever talks to. It decides whether a plane can land based on the state it holds, and no aircraft ever contacts another aircraft directly.</p>
<pre><code class="language-csharp">// The mediator interface
public interface IControlTower
{
    void RequestLanding(Aircraft requester);
}
</code></pre>
<pre><code class="language-csharp">// The concrete mediator, coordinates all the aircraft instead of letting them talk to each other
public class ControlTower : IControlTower
{
    private readonly List&lt;Aircraft&gt; _aircraft = new();
    private bool _runwayFree = true;

    public void Register(Aircraft aircraft) =&gt; _aircraft.Add(aircraft);

    public void RequestLanding(Aircraft requester)
    {
        if (_runwayFree)
        {
            _runwayFree = false;
            Console.WriteLine($"Tower: Runway clear. {requester.Name}, you are cleared to land.");
        }
        else
        {
            Console.WriteLine($"Tower: Runway occupied. {requester.Name}, please hold your position.");
        }
    }
}
</code></pre>
<pre><code class="language-csharp">// The colleague, only ever talks to the mediator, never to other aircraft directly
public class Aircraft
{
    public string Name { get; }

    private readonly IControlTower _tower;

    public Aircraft(string name, IControlTower tower)
    {
        Name   = name;
        _tower = tower;
    }

    public void RequestLanding()
    {
        Console.WriteLine($"{Name}: Requesting permission to land.");
        _tower.RequestLanding(this);
    }
}
</code></pre>
<p>Now let's see it in action:</p>
<pre><code class="language-csharp">var tower = new ControlTower();

var flight101 = new Aircraft("Flight 101", tower);
var flight202 = new Aircraft("Flight 202", tower);

tower.Register(flight101);
tower.Register(flight202);

flight101.RequestLanding();
flight202.RequestLanding();
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="language-yaml">Flight 101: Requesting permission to land.
Tower: Runway clear. Flight 101, you are cleared to land.
Flight 202: Requesting permission to land.
Tower: Runway occupied. Flight 202, please hold your position.
</code></pre>
<p>Flight 101 and Flight 202 never spoke to each other. Neither one even knows the other exists. Both only ever talked to the tower, and the tower decided what happened next. That's the Mediator pattern.</p>
<h4 id="heading-when-to-use-it">When to Use it</h4>
<p>Use Mediator when a group of objects communicate in complex, tangled ways, and you want to centralise that communication.</p>
<p>It's also helpful when you want to reuse objects independently, without them being locked together by direct references to each other.</p>
<p>And reach for it when the way objects interact changes often, and you'd rather change it in one place than in every object involved.</p>
<h3 id="heading-6-the-memento-design-pattern">6. The Memento Design Pattern</h3>
<h4 id="heading-real-world-example">Real World Example</h4>
<p>Think of the undo history in a text editor. Every so often, the editor quietly takes a snapshot of what the document looks like. It doesn't ask the document to expose its internals to do this. It just captures a copy of the content at that moment.</p>
<p>When you press undo, the editor hands that snapshot back, and the document restores itself to exactly how it was. The history keeps a pile of these snapshots, but it never looks inside them or changes them. It only stores them and hands them back.</p>
<p>That's the Memento pattern. It lets you capture and restore an object's state without exposing how that state is structured internally.</p>
<h4 id="heading-problems-it-solves">Problems it solves:</h4>
<ul>
<li><p>What if undo required exposing every private field of the document? That would break encapsulation, and any change to the document's internals would ripple out to whatever handles undo. The memento hides that structure inside an object only the document itself knows how to read.</p>
</li>
<li><p>What if the history needed to inspect or modify old snapshots? It shouldn't be able to. The caretaker only stores and returns mementos, it never reads or changes what's inside them.</p>
</li>
<li><p>What if you needed several restore points, not just one? Because each memento is just an object, they can be stacked, listed, or discarded, giving you as many restore points as you want to keep.</p>
</li>
</ul>
<p>In simple terms, you capture an object's state in a snapshot you can restore later, without exposing how that state is put together internally.</p>
<p>Wikipedia describes it like this:</p>
<blockquote>
<p><em>"The memento pattern is a software design pattern that provides the ability to restore an object to its previous state (undo via rollback)."</em></p>
<p><strong>(</strong><a href="https://en.wikipedia.org/wiki/Memento_pattern">Source</a>)</p>
</blockquote>
<h4 id="heading-programming-example">Programming Example:</h4>
<p><code>TextEditor</code> is the originator: it creates <code>EditorMemento</code> snapshots of itself and can restore from one. <code>History</code> is the caretaker: it stores mementos on a stack without ever looking inside them.</p>
<pre><code class="language-csharp">// The memento, an immutable snapshot of the editor's state
public class EditorMemento
{
    public string Content { get; }

    public EditorMemento(string content) =&gt; Content = content;
}
</code></pre>
<pre><code class="language-csharp">// The originator, creates and restores from mementos of its own state
public class TextEditor
{
    public string Content { get; private set; } = string.Empty;

    public void Write(string text) =&gt; Content += text;

    public EditorMemento Save() =&gt; new(Content);

    public void Restore(EditorMemento memento) =&gt; Content = memento.Content;
}
</code></pre>
<pre><code class="language-csharp">// The caretaker, stores mementos without ever looking inside them
public class History
{
    private readonly Stack&lt;EditorMemento&gt; _snapshots = new();

    public void Save(EditorMemento memento) =&gt; _snapshots.Push(memento);

    public EditorMemento Undo() =&gt; _snapshots.Pop();
}
</code></pre>
<p>Now let's see it in action:</p>
<pre><code class="language-csharp">var editor  = new TextEditor();
var history = new History();

editor.Write("Hello");
history.Save(editor.Save());

editor.Write(", world");
history.Save(editor.Save());

editor.Write("!!!");
Console.WriteLine($"Current: {editor.Content}");

editor.Restore(history.Undo());
Console.WriteLine($"After undo: {editor.Content}");

editor.Restore(history.Undo());
Console.WriteLine($"After undo: {editor.Content}");
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="language-yaml">Current: Hello, world!!!
After undo: Hello, world
After undo: Hello
</code></pre>
<p><code>History</code> never read or changed the text inside a snapshot. It just pushed mementos on and popped them off. Only <code>TextEditor</code> knew what to do with the content inside one. That's the Memento pattern.</p>
<h4 id="heading-when-to-use-it">When to Use it</h4>
<p>Use Memento when you need undo/redo functionality and want to capture state without exposing an object's internals.</p>
<p>It's also a good choice when taking a snapshot directly would break encapsulation by exposing private fields.</p>
<p>And it's helpful when you want the object that stores history to stay dumb: like holding snapshots without knowing or caring what's inside them.</p>
<h3 id="heading-7-the-observer-design-pattern">7. The Observer Design Pattern</h3>
<h4 id="heading-real-world-example">Real World Example</h4>
<p>Think of subscribing to a YouTube channel. You don't sit there refreshing the page, checking if a new video has been uploaded. You subscribe once, and the moment the channel uploads something, you get notified automatically.</p>
<p>The channel doesn't know or care what each subscriber does with that notification. It just knows it has a list of subscribers, and when something changes, it tells all of them.</p>
<p>That's the Observer pattern. One object holds a list of dependents, and whenever its state changes, it notifies every one of them automatically.</p>
<h4 id="heading-problems-it-solves">Problems it solves:</h4>
<ul>
<li><p>What if every subscriber had to keep checking the channel for updates? That would waste effort and add delay. The channel notifying its subscribers directly means they find out the moment it happens.</p>
</li>
<li><p>What if the channel had to know exactly what each subscriber wanted to do with a new video? It shouldn't need to. The channel only calls <code>Notify()</code>, each subscriber decides for itself what that means.</p>
</li>
<li><p>What if you wanted to add or remove subscribers at runtime? The channel doesn't need to change. It just keeps a list, and subscribing or unsubscribing only ever affects that list.</p>
</li>
</ul>
<p>In simple terms, one object keeps a list of dependents and automatically notifies all of them whenever its own state changes.</p>
<p>Wikipedia describes it like this:</p>
<blockquote>
<p><em>"The observer pattern is a software design pattern in which an object, named the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods."</em> <a href="https://en.wikipedia.org/wiki/Observer_pattern">(Source</a>)</p>
</blockquote>
<h4 id="heading-programming-example">Programming Example:</h4>
<p><code>YouTubeChannel</code> is the subject: it keeps a list of <code>ISubscriber</code>s and notifies all of them whenever a video is uploaded. <code>Subscriber</code> is the concrete observer, deciding for itself what to do with that notification.</p>
<pre><code class="language-csharp">// The observer interface, every subscriber implements this
public interface ISubscriber
{
    void Notify(string channelName, string videoTitle);
}
</code></pre>
<pre><code class="language-csharp">// The concrete observer
public class Subscriber : ISubscriber
{
    private readonly string _name;

    public Subscriber(string name) =&gt; _name = name;

    public void Notify(string channelName, string videoTitle)
    {
        Console.WriteLine($"{_name}: {channelName} just uploaded '{videoTitle}'!");
    }
}
</code></pre>
<pre><code class="language-csharp">// The subject, keeps track of its subscribers and notifies them of changes
public class YouTubeChannel
{
    private readonly string _name;
    private readonly List&lt;ISubscriber&gt; _subscribers = new();

    public YouTubeChannel(string name) =&gt; _name = name;

    public void Subscribe(ISubscriber subscriber)   =&gt; _subscribers.Add(subscriber);
    public void Unsubscribe(ISubscriber subscriber) =&gt; _subscribers.Remove(subscriber);

    public void UploadVideo(string title)
    {
        Console.WriteLine($"{_name}: Uploaded '{title}'.");

        foreach (var subscriber in _subscribers)
        {
            subscriber.Notify(_name, title);
        }
    }
}
</code></pre>
<p>Now let's see it in action:</p>
<pre><code class="language-csharp">var channel = new YouTubeChannel("Code With Isaiah");

var alice = new Subscriber("Alice");
var bob   = new Subscriber("Bob");

channel.Subscribe(alice);
channel.Subscribe(bob);

channel.UploadVideo("Design Patterns Explained");

channel.Unsubscribe(bob);
channel.UploadVideo("Understanding the Observer Pattern");
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="language-yaml">Code With Isaiah: Uploaded 'Design Patterns Explained'.
Alice: Code With Isaiah just uploaded 'Design Patterns Explained'!
Bob: Code With Isaiah just uploaded 'Design Patterns Explained'!
Code With Isaiah: Uploaded 'Understanding the Observer Pattern'.
Alice: Code With Isaiah just uploaded 'Understanding the Observer Pattern'!
</code></pre>
<p>Once Bob unsubscribed, he stopped hearing about new uploads entirely. The channel never singled him out, it just no longer had him on the list it notifies. That's the Observer pattern.</p>
<h4 id="heading-when-to-use-it">When to Use it</h4>
<p>Use Observer when a change to one object should automatically update an unknown number of others.</p>
<p>It's also useful when you want objects to stay loosely coupled: the subject only knows about an observer interface, never concrete details.</p>
<p>And it's a good option when the number of dependents can grow or shrink at runtime, such as subscribing and unsubscribing.</p>
<h3 id="heading-8-the-state-design-pattern">8. The State Design Pattern</h3>
<h4 id="heading-real-world-example">Real World Example</h4>
<p>Think of an online order moving through its lifecycle: pending, then shipped, then delivered. What "moving to the next step" actually means is different at every stage. From pending it means handing the package to a courier. From shipped it means marking it as received. From delivered, there's nowhere left to go. Rather than one giant method full of <code>if</code> checks for every possible stage, each stage can just know what comes after it.</p>
<p>That's the State pattern. The object's behaviour changes based on its current state, and each state knows how to transition to the next one.</p>
<h4 id="heading-problems-it-solves">Problems it solves:</h4>
<ul>
<li><p>What if one method had to handle every stage with a long chain of conditionals? It would grow harder to follow every time a new stage was added. Giving each stage its own class keeps the logic for that stage self-contained.</p>
</li>
<li><p>What if adding a new stage meant editing that same giant method? It's easy to introduce a bug in an unrelated stage while doing so. A new state is just a new class, dropped in alongside the others.</p>
</li>
<li><p>What if the object needed to behave completely differently depending on where it was in its lifecycle? Delegating to the current state object means the context doesn't need to know the details. It just asks the current state what to do.</p>
</li>
</ul>
<p>In simple terms, you let an object change its behaviour by changing which state object it's currently holding, so the object appears to change how it acts as its state changes.</p>
<p>Wikipedia describes it like this:</p>
<blockquote>
<p><em>"The state pattern is a behavioral software design pattern that allows an object to alter its behavior when its internal state changes. This pattern is close to the concept of finite-state machines."</em> <strong>(</strong><a href="https://en.wikipedia.org/wiki/State_pattern">Source</a>)</p>
</blockquote>
<h4 id="heading-programming-example">Programming Example:</h4>
<p><code>Order</code> is the context: it holds whatever <code>IOrderState</code> it's currently in and delegates to it. Each concrete state, <code>PendingState</code>, <code>ShippedState</code>, <code>DeliveredState</code>, knows what the next state should be.</p>
<pre><code class="language-csharp">// The state interface, every state implements this
public interface IOrderState
{
    void Next(Order order);
    string Name { get; }
}
</code></pre>
<pre><code class="language-csharp">// The context, delegates behaviour to whatever state it currently holds
public class Order
{
    public IOrderState State { get; set; } = new PendingState();

    public void Next()
    {
        Console.WriteLine($"Order is currently: {State.Name}");
        State.Next(this);
    }
}
</code></pre>
<pre><code class="language-csharp">// Concrete states, each knows what comes after it
public class PendingState : IOrderState
{
    public string Name =&gt; "Pending";

    public void Next(Order order) =&gt; order.State = new ShippedState();
}

public class ShippedState : IOrderState
{
    public string Name =&gt; "Shipped";

    public void Next(Order order) =&gt; order.State = new DeliveredState();
}

public class DeliveredState : IOrderState
{
    public string Name =&gt; "Delivered";

    public void Next(Order order)
    {
        Console.WriteLine("Order has already been delivered. Nothing left to do.");
    }
}
</code></pre>
<p>Now let's see it in action:</p>
<pre><code class="language-csharp">var order = new Order();

order.Next();
order.Next();
order.Next();
order.Next();
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="language-json">Order is currently: Pending
Order is currently: Shipped
Order is currently: Delivered
Order has already been delivered. Nothing left to do.
</code></pre>
<p><code>Order</code> never checked "if pending, do this, if shipped, do that." It just asked its current state what to do next, and the state itself decided what came after. That's the State pattern.</p>
<h4 id="heading-when-to-use-it">When to Use it</h4>
<p>Use State when an object's behaviour depends on its state, and it must change that behaviour at runtime as the state changes.</p>
<p>It's also helpful when you have large conditional blocks that branch on the object's current state or type.</p>
<p>And choose it when transitions between states should be explicit and self-contained, rather than scattered across one big method.</p>
<h3 id="heading-9-the-strategy-design-pattern">9. The Strategy Design Pattern</h3>
<h4 id="heading-real-world-example">Real World Example</h4>
<p>Think of checking out of an online store. You can pay by credit card, or you can pay through PayPal. The shopping cart doesn't care which one you pick. It just knows the total, hands it to whichever payment method you chose, and lets that method handle the details of actually charging you. Swap the payment method, and the cart's own code never changes.</p>
<p>That's the Strategy pattern. An algorithm (in this case "how to pay") is pulled out into its own interchangeable object, and the client just picks which one to use.</p>
<h4 id="heading-problems-it-solves">Problems it solves:</h4>
<ul>
<li><p>What if the cart had a big <code>if/else</code> for every payment method? Adding a new one would mean editing that method every time. Pulling each payment method out into its own class means the cart never needs to change.</p>
</li>
<li><p>What if you wanted to swap the algorithm at runtime? A hardcoded method can't be swapped. A strategy object can simply be replaced with another one that implements the same interface.</p>
</li>
<li><p>What if two different payment methods needed to share a common interface but nothing else? Each one implements the strategy interface, but its internal details (a card number here, an email there) stay private to it.</p>
</li>
</ul>
<p>In simple terms, you pull an algorithm out into its own interchangeable object, so the class using it doesn't need to know or care which specific version is running.</p>
<p>Wikipedia describes it like this:</p>
<blockquote>
<p><em>"The strategy pattern is a behavioral software design pattern that enables selecting an algorithm at runtime."</em> <a href="https://en.wikipedia.org/wiki/Strategy_pattern">(Source</a>)</p>
</blockquote>
<h4 id="heading-programming-example">Programming Example:</h4>
<p><code>ShoppingCart</code> is the context: it holds an <code>IPaymentStrategy</code> and delegates the actual payment to it. <code>CreditCardPayment</code> and <code>PayPalPayment</code> are concrete strategies, each a different way to pay.</p>
<pre><code class="language-csharp">// The strategy interface, every payment method implements this
public interface IPaymentStrategy
{
    void Pay(decimal amount);
}
</code></pre>
<pre><code class="language-csharp">// Concrete strategies, each a different way to pay
public class CreditCardPayment : IPaymentStrategy
{
    private readonly string _cardNumber;

    public CreditCardPayment(string cardNumber) =&gt; _cardNumber = cardNumber;

    public void Pay(decimal amount)
    {
        Console.WriteLine($"Charged ${amount} to credit card ending in {_cardNumber[^4..]}.");
    }
}

public class PayPalPayment : IPaymentStrategy
{
    private readonly string _email;

    public PayPalPayment(string email) =&gt; _email = email;

    public void Pay(decimal amount)
    {
        Console.WriteLine($"Charged ${amount} via PayPal account {_email}.");
    }
}
</code></pre>
<pre><code class="language-csharp">// The context, holds a strategy and delegates the actual payment work to it
public class ShoppingCart
{
    private readonly decimal _total;
    private IPaymentStrategy? _paymentMethod;

    public ShoppingCart(decimal total) =&gt; _total = total;

    public void SetPaymentMethod(IPaymentStrategy method) =&gt; _paymentMethod = method;

    public void Checkout()
    {
        if (_paymentMethod is null)
        {
            Console.WriteLine("No payment method selected.");
            return;
        }

        _paymentMethod.Pay(_total);
    }
}
</code></pre>
<p>Now let's see it in action:</p>
<pre><code class="language-csharp">var cart = new ShoppingCart(59.99m);

cart.SetPaymentMethod(new CreditCardPayment("4111 1111 1111 1111"));
cart.Checkout();

cart.SetPaymentMethod(new PayPalPayment("isaiah@example.com"));
cart.Checkout();
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="language-json">Charged $59.99 to credit card ending in 1111.
Charged $59.99 via PayPal account isaiah@example.com.
</code></pre>
<p><code>ShoppingCart</code> never knew how a payment actually got processed. It just called <code>Pay()</code> on whatever strategy it was holding at the time. That's the Strategy pattern: the algorithm is swapped out, the class using it stays exactly the same.</p>
<h4 id="heading-when-to-use-it">When to Use it</h4>
<p>Use Strategy when you have several variants of an algorithm, and want to switch between them at runtime.</p>
<p>It's also helpful when you want to avoid a class full of conditionals that pick behaviour based on a type or flag.</p>
<p>And it's a solid choice when related classes only differ in the behaviour they use, and that behaviour should be interchangeable.</p>
<h3 id="heading-10-the-template-method-design-pattern">10. The Template Method Design Pattern</h3>
<h4 id="heading-real-world-example">Real World Example</h4>
<p>Think of making a hot drink, tea or coffee. Both follow the exact same basic steps: boil water, brew, pour into a cup, and add something to taste. What differs is only two of those steps: tea gets steeped, and coffee gets brewed through grounds. Tea gets lemon, and coffee gets sugar and milk. The overall recipe never changes, only the specific details of a couple of steps within it.</p>
<p>That's the Template Method pattern. A base class defines the fixed skeleton of an algorithm, and subclasses only fill in the steps that are actually allowed to vary.</p>
<h4 id="heading-problems-it-solves">Problems it solves:</h4>
<ul>
<li><p>What if every beverage repeated the entire recipe from scratch? Boiling water and pouring into a cup would be duplicated in every single class. The template method keeps those steps in one place, written once.</p>
</li>
<li><p>What if a subclass could reorder the steps, or skip one entirely? That would let each beverage break the overall recipe. Because the algorithm's skeleton lives in the base class as a single method, the order and structure stay fixed.</p>
</li>
<li><p>What if you wanted to add a new beverage? Only the steps that differ, brewing and condiments, need to be written. Everything else is already handled by the base class.</p>
</li>
</ul>
<p>In simple terms, you define the fixed skeleton of an algorithm in a base class, and let subclasses fill in only the steps that are actually allowed to differ.</p>
<p>Wikipedia describes it like this:</p>
<blockquote>
<p><em>"In object-oriented programming, the template method is one of the behavioral design patterns identified by Gamma et al. in the book Design Patterns. The template method is a method in a superclass, usually an abstract superclass, and defines the skeleton of an operation in terms of a number of high-level steps." (</em><a href="https://en.wikipedia.org/wiki/Template_method_pattern">Source</a>)</p>
</blockquote>
<h4 id="heading-programming-example">Programming Example:</h4>
<p><code>Beverage</code> defines <code>Prepare()</code> as the template method: the fixed sequence of steps. <code>Tea</code> and <code>Coffee</code> only override <code>Brew()</code> and <code>AddCondiments()</code>, the two steps that are actually allowed to vary.</p>
<pre><code class="language-csharp">// The abstract class, defines the skeleton of the algorithm
public abstract class Beverage
{
    // The template method, the steps and their order never change
    public void Prepare()
    {
        BoilWater();
        Brew();
        PourInCup();
        AddCondiments();
    }

    private void BoilWater() =&gt; Console.WriteLine("Boiling water.");
    private void PourInCup() =&gt; Console.WriteLine("Pouring into cup.");

    // Steps left for subclasses to fill in
    protected abstract void Brew();
    protected abstract void AddCondiments();
}
</code></pre>
<pre><code class="language-csharp">// A concrete class, fills in the steps specific to tea
public class Tea : Beverage
{
    protected override void Brew() =&gt; Console.WriteLine("Steeping the tea bag.");
    protected override void AddCondiments() =&gt; Console.WriteLine("Adding lemon.");
}

// Another concrete class, fills in the steps specific to coffee
public class Coffee : Beverage
{
    protected override void Brew() =&gt; Console.WriteLine("Brewing the coffee grounds.");
    protected override void AddCondiments() =&gt; Console.WriteLine("Adding sugar and milk.");
}
</code></pre>
<p>Now let's see it in action:</p>
<pre><code class="language-csharp">Beverage tea    = new Tea();
Beverage coffee = new Coffee();

tea.Prepare();
Console.WriteLine();
coffee.Prepare();
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="language-yaml">Boiling water.
Steeping the tea bag.
Pouring into cup.
Adding lemon.

Boiling water.
Brewing the coffee grounds.
Pouring into cup.
Adding sugar and milk.
</code></pre>
<p>Both drinks boiled water and poured into a cup in exactly the same way, because <code>Prepare()</code> in the base class handled that. Only brewing and condiments changed, because those were the steps each subclass was actually responsible for. That's the Template Method pattern.</p>
<h4 id="heading-when-to-use-it">When to Use it</h4>
<p>Use Template Method when several classes share the same overall algorithm, but differ in a few specific steps.</p>
<p>It's a good choice when you want to enforce a fixed sequence of steps, while still letting subclasses customise parts of it.</p>
<p>And it's helpful when you want to avoid duplicating the parts of an algorithm that never change across every subclass.</p>
<h3 id="heading-11-the-visitor-design-pattern">11. The Visitor Design Pattern</h3>
<h4 id="heading-real-world-example">Real World Example</h4>
<p>Think of a shopping cart with different kinds of items: books and electronics, each taxed differently at checkout. You don't want to bake pricing logic into the <code>Book</code> and <code>Electronic</code> classes themselves, especially if you'll need other operations on them later too, like generating a shipping label or a warranty summary. Instead, each item just accepts a visitor and hands itself over. The visitor is the one that actually knows how to price a book differently from an electronic.</p>
<p>That's the Visitor pattern. The operation lives outside the objects it acts on, and each object just lets the visitor know what it needs to know: what type of thing it actually is.</p>
<h4 id="heading-problems-it-solves">Problems it solves:</h4>
<ul>
<li><p>What if pricing logic was written directly inside <code>Book</code> and <code>Electronic</code>? Every new operation (tax, shipping, warranty) would mean editing both classes again and again. The visitor keeps each new operation in its own self-contained class instead.</p>
</li>
<li><p>What if you needed to add a new operation without touching the existing item classes? Normally that means modifying every class the operation applies to. A new visitor is a new class, while <code>Book</code> and <code>Electronic</code> never change.</p>
</li>
<li><p>What if a generic loop had to guess the concrete type of each item? That usually means a chain of type checks. <code>Accept()</code> calling <code>Visit(this)</code> lets the compiler pick the right overload automatically, without a single <code>if</code> or type check.</p>
</li>
</ul>
<p>In simple terms, you move an operation out of the objects it acts on and into its own class. Each object just accepts a visitor and lets it know what concrete type it is.</p>
<p>Wikipedia describes it like this:</p>
<blockquote>
<p><em>"The visitor design pattern is a way of separating an algorithm from an object structure on which it operates." (</em><a href="https://en.wikipedia.org/wiki/Visitor_pattern">Source</a>)</p>
</blockquote>
<h4 id="heading-programming-example">Programming Example:</h4>
<p><code>Book</code> and <code>Electronic</code> both implement <code>IItem</code> and simply call <code>visitor.Visit(this)</code>. <code>PricingVisitor</code> implements <code>IVisitor</code> with an overload for each concrete type, so the right pricing logic runs automatically.</p>
<pre><code class="language-csharp">// The element interface, every item in the cart implements this
public interface IItem
{
    void Accept(IVisitor visitor);
}
</code></pre>
<pre><code class="language-csharp">// Concrete elements, each accepts a visitor and hands itself over
public class Book : IItem
{
    public string Title { get; }
    public decimal Price { get; }

    public Book(string title, decimal price)
    {
        Title = title;
        Price = price;
    }

    public void Accept(IVisitor visitor) =&gt; visitor.Visit(this);
}

public class Electronic : IItem
{
    public string Name { get; }
    public decimal Price { get; }

    public Electronic(string name, decimal price)
    {
        Name  = name;
        Price = price;
    }

    public void Accept(IVisitor visitor) =&gt; visitor.Visit(this);
}
</code></pre>
<pre><code class="language-csharp">// The visitor interface, one Visit overload per concrete element
public interface IVisitor
{
    void Visit(Book book);
    void Visit(Electronic electronic);
}
</code></pre>
<pre><code class="language-csharp">// A concrete visitor, adds a new operation without touching Book or Electronic
public class PricingVisitor : IVisitor
{
    public decimal Total { get; private set; }

    public void Visit(Book book)
    {
        Console.WriteLine($"Book: {book.Title} — ${book.Price:F2} (no tax).");
        Total += book.Price;
    }

    public void Visit(Electronic electronic)
    {
        var priceWithTax = electronic.Price * 1.15m;
        Console.WriteLine($"Electronic: {electronic.Name} — ${priceWithTax:F2} (with 15% tax).");
        Total += priceWithTax;
    }
}
</code></pre>
<p>Now let's see it in action:</p>
<pre><code class="language-csharp">var cart = new List&lt;IItem&gt;
{
    new Book("Design Patterns", 45.00m),
    new Electronic("Headphones", 120.00m)
};

var pricingVisitor = new PricingVisitor();

foreach (var item in cart)
{
    item.Accept(pricingVisitor);
}

Console.WriteLine($"Total: ${pricingVisitor.Total:F2}");
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="language-yaml">Book: Design Patterns — $45.00 (no tax).
Electronic: Headphones — $138.00 (with 15% tax).
Total: $183.00
</code></pre>
<p>Neither <code>Book</code> nor <code>Electronic</code> contained a single line of pricing logic. Each one only knew how to <code>Accept()</code> a visitor. <code>PricingVisitor</code> was the one that actually decided how each type gets priced. That's the Visitor pattern: the operation lives outside the object structure, not inside it.</p>
<h4 id="heading-when-to-use-it">When to Use it</h4>
<p>Use Visitor when you need to perform operations across a group of unrelated classes, without polluting each class with that logic.</p>
<p>It's also helpful when you want to add new operations often, but the object structure itself rarely changes.</p>
<p>And it's a good choice when you'd otherwise need type checks or casting to figure out what to do with each object in a collection.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>That covers all 23 classic design patterns across the three families: Creational, Structural, and Behavioral.</p>
<p>None of them are rules you must follow. They're answers to problems that show up again and again in software: how to create objects without hard-coding their exact type, how to compose bigger structures out of smaller ones, and how to let objects communicate without being tightly bound to each other.</p>
<p>A few things worth remembering:</p>
<ul>
<li><p>You won't use most of these patterns most of the time. Recognising <em>when a problem calls for one</em> is the actual skill. Forcing a pattern onto a problem that doesn't need it usually makes the code harder to follow, not easier.</p>
</li>
<li><p>The real world analogies exist to build intuition, not to be taken literally. Once a pattern's shape clicks in a story you understand, spotting it in real code becomes far easier.</p>
</li>
<li><p>Patterns compose. A Factory Method might produce objects that are themselves Decorators. A Composite tree might be built with a Builder. Real systems mix and layer patterns rather than using them in isolation.</p>
</li>
<li><p>The language doesn't matter. Every example here is in C#, but the same shapes exist in Python, Java, TypeScript, Go, Rust, and beyond. If you understand the <em>problem</em> a pattern solves, translating it to any language is straightforward.</p>
</li>
</ul>
<p>The goal isn't to memorise 23 names. It's to recognise the recurring problems underneath them, so that when one shows up in your own code, you already know a proven shape for solving it.</p>
<blockquote>
<p><em>"Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice."</em></p>
<p><strong>Source:</strong> Christopher Alexander, <em>A Pattern Language</em> — the architectural work that originally inspired software design patterns.</p>
</blockquote>
<p>If this handbook was useful, the source lives at <a href="https://github.com/Clifftech123/design-patterns-handbook">github.com/Clifftech123/design-patterns-handbook</a>. Star it, fork it, or open a PR with a pattern you think is missing.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Embedded Swift: A Modern Approach to Low-Level Programming ]]>
                </title>
                <description>
                    <![CDATA[ Embedded programming has long been dominated by C and C++, powering everything from microcontrollers to real-time systems. While these languages offer unmatched low-level control, they also introduce persistent challenges, manual memory management, u... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/embedded-swift-a-modern-approach-to-low-level-programming/</link>
                <guid isPermaLink="false">688d5fc7d30be1cecdacf767</guid>
                
                    <category>
                        <![CDATA[ embedded systems ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Firmware Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Swift ]]>
                    </category>
                
                    <category>
                        <![CDATA[ C ]]>
                    </category>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Programming Blogs ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ memory-management ]]>
                    </category>
                
                    <category>
                        <![CDATA[ programming languages ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Soham Banerjee ]]>
                </dc:creator>
                <pubDate>Sat, 02 Aug 2025 00:45:59 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1754090186842/80a42dca-f2c4-49de-b704-2e90134c6397.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Embedded programming has long been dominated by C and C++, powering everything from microcontrollers to real-time systems. While these languages offer unmatched low-level control, they also introduce persistent challenges, manual memory management, unsafe pointer operations, and subtle logic bugs stemming from weak type systems and undefined behavior.</p>
<p>With the release of Swift 6 and its new Embedded Swift compilation mode, developers now have access to a modern, memory-safe, and performant alternative that’s tailored specifically for resource-constrained systems.</p>
<p>While languages like Rust have also emerged to address these issues, Embedded Swift brings the clarity and safety of Swift to microcontroller environments, without giving up on determinism, binary size, or hardware access.</p>
<p>This article introduces Embedded Swift and explores how it compares to traditional C/C++ development. We’ll cover its key features, programming and memory models, how to set up the toolchain for STM32 microcontrollers, and how to link Swift with existing C drivers.</p>
<p>Along the way, we’ll examine performance trade-offs, growing ecosystem support, and the broader industry movement toward memory-safe languages. As I hope you’ll see, Swift is a serious contender in the future of embedded development.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>To get the most out of this article, you should have a basic understanding of programming in Swift and C. Familiarity with embedded hardware platforms and firmware development concepts will also be helpful.</p>
<p>If you're new to embedded systems, consider reviewing this <a target="_blank" href="https://www.freecodecamp.org/news/learn-embedded-systems-firmware-basics-handbook-for-devs/">introductory guide to embedded firmware</a> to build foundational knowledge before diving into Embedded Swift.</p>
<h2 id="heading-scope">Scope</h2>
<p>This article is intended as a practical introduction to Embedded Swift. It covers:</p>
<ul>
<li><p>An overview of Embedded Swift and its key language features</p>
</li>
<li><p>Swift’s programming and memory model in an embedded context</p>
</li>
<li><p>Setting up the Embedded Swift toolchain on macOS for STM32 microcontrollers</p>
</li>
<li><p>Interoperability with C code and linking to existing low-level drivers</p>
</li>
<li><p>A look at memory and instruction-level performance</p>
</li>
<li><p>Future directions and use cases for Embedded Swift</p>
</li>
</ul>
<p>Note that this article does not provide a full tutorial on the Swift language itself. While the primary focus is on STM32, similar principles apply to other supported platforms such as ESP32, Raspberry Pi Pico, and nRF52.</p>
<h2 id="heading-table-of-contents">Table of Contents:</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-swift-what-is-embedded-swift">What is Swift? What is Embedded Swift?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-swift-programming-model">Swift Programming Model</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-swift-memory-management">Swift Memory Management</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-memory-and-instruction-cycle-comparison">Memory and Instruction Cycle Comparison</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-setup-embedded-swift">How to Setup Embedded Swift</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-c-swift-linkages">C-Swift Linkages:</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-future-work">Future Work</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-what-is-swift-what-is-embedded-swift">What is Swift? What is Embedded Swift?</h2>
<p>Swift is a modern programming language developed by Apple that combines the performance of compiled languages with the expressiveness and safety of modern language design. While Swift was originally created for iOS and macOS development, it has evolved into a powerful general-purpose language used in server-side development, systems programming, and increasingly, embedded systems.</p>
<p>Embedded Swift is a special compilation mode introduced in Swift 6 that brings the benefits of Swift to resource-constrained platforms like microcontrollers. It lets developers use a safe, high-level language while still producing compact, deterministic, and performant binaries suitable for embedded applications.</p>
<h3 id="heading-key-features-of-swift">Key Features of Swift</h3>
<p>Embedded Swift retains many of the powerful language features that make Swift an attractive alternative to C/C++ in embedded development:</p>
<p><strong>Type Safety</strong>: Swift uses a strong static type system, which prevents many programming errors at compile time. Unlike C, where type mismatches can result in undefined behavior, Swift ensures all types are used correctly before code even runs.</p>
<p><strong>Strict Type Checking</strong>: Swift doesn't allow implicit type conversions that could lose data or cause unexpected behavior. For example:</p>
<pre><code class="lang-swift"><span class="hljs-comment">// This won't compile in Swift</span>
<span class="hljs-keyword">let</span> integer: <span class="hljs-type">Int</span> = <span class="hljs-number">42</span>
<span class="hljs-keyword">let</span> decimal: <span class="hljs-type">Double</span> = <span class="hljs-number">3.14</span>
<span class="hljs-keyword">let</span> result = integer + decimal  <span class="hljs-comment">// Error: Cannot convert value of type 'Int' to expected argument type 'Double'</span>

<span class="hljs-comment">// You must be explicit about conversions</span>
<span class="hljs-keyword">let</span> result = <span class="hljs-type">Double</span>(integer) + decimal  <span class="hljs-comment">// Correct</span>
</code></pre>
<p><strong>Non-nullable Types by Default</strong>: In C, pointers can be null by default, which introduces risk. In Swift, variables cannot be nil unless explicitly marked as optionals:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">var</span> name: <span class="hljs-type">String</span> = <span class="hljs-string">"John"</span>
name = <span class="hljs-literal">nil</span>  <span class="hljs-comment">// Compile error - String cannot be nil</span>

<span class="hljs-keyword">var</span> optionalName: <span class="hljs-type">String?</span> = <span class="hljs-string">"John"</span>
optionalName = <span class="hljs-literal">nil</span>  <span class="hljs-comment">// This is allowed</span>
</code></pre>
<h4 id="heading-memory-safety-via-arc-covered-in-detail-later">Memory Safety via ARC (Covered in detail later):</h4>
<p>Swift manages memory automatically using Automatic Reference Counting (ARC). Unlike manual memory management in C/C++, ARC handles object lifecycles efficiently without unpredictable garbage collection pauses. We'll cover ARC and its impact in embedded contexts in a dedicated section later.</p>
<p><strong>Modern Syntax</strong>:<br>Swift's syntax is clean, consistent, and designed for readability. It supports modern paradigms including:</p>
<ul>
<li><p>Functional programming (map, filter, reduce)</p>
</li>
<li><p>Generics (type-safe abstractions)</p>
</li>
<li><p>Protocol-Oriented Programming (discussed in the next section)</p>
</li>
</ul>
<p>These features allow you to write more expressive and maintainable code compared to procedural C or inheritance-heavy C++.</p>
<p><strong>Performance</strong>:<br>Swift is designed to perform on par with C++ in many scenarios. Optimizations such as inlining, dead code elimination, and static dispatch help ensure that high-level abstractions don’t compromise performance. In embedded mode, Swift disables features like runtime reflection and dynamic dispatch to further reduce overhead.</p>
<p>To fully leverage Swift for embedded development, it's important to understand its programming model. Unlike C’s procedural approach or C++’s class-heavy design, Swift promotes protocol-oriented programming and composition, which offers both flexibility and safety in embedded system design.</p>
<h2 id="heading-swift-programming-model">Swift Programming Model</h2>
<p>Swift embraces a multi-paradigm programming model that blends object-oriented, functional, and protocol-oriented programming, all underpinned by strong type safety and memory safety.</p>
<p>For embedded developers coming from C or C++, this model may feel different at first. But it provides a more modular and testable way to build complex systems, something especially valuable in embedded applications where hardware abstraction and strict reliability are critical.</p>
<h3 id="heading-protocol-oriented-programming-pop">Protocol-Oriented Programming (POP)</h3>
<p>Swift emphasizes protocols over inheritance, encouraging developers to define behaviors through protocols and implement them using value types like <code>struct</code> and <code>enum</code>, rather than relying heavily on classes.</p>
<p>This philosophy favors composition over inheritance, allowing you to build complex functionality by combining smaller, well-defined components.</p>
<p>Key Concepts<strong>:</strong></p>
<ul>
<li><p><code>protocol</code> defines required behavior.</p>
</li>
<li><p>Protocol extensions provide default behavior.</p>
</li>
<li><p>Prefer value semantics using <code>struct</code>.</p>
</li>
</ul>
<p>Example<strong>:</strong></p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">protocol</span> <span class="hljs-title">Speakable</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">speak</span><span class="hljs-params">()</span></span>
}

<span class="hljs-class"><span class="hljs-keyword">extension</span> <span class="hljs-title">Speakable</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">speak</span><span class="hljs-params">()</span></span> {
        <span class="hljs-built_in">print</span>(<span class="hljs-string">"Default sound"</span>)
    }
}

<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Dog</span>: <span class="hljs-title">Speakable</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">speak</span><span class="hljs-params">()</span></span> {
        <span class="hljs-built_in">print</span>(<span class="hljs-string">"Woof!"</span>)
    }
}
</code></pre>
<p>Embedded Swift uses protocols with static dispatch. With static dispatch, the compiler knows the exact memory address of the function to call and can generate a direct jump instruction. There's no runtime lookup, no indirection, and no uncertainty.</p>
<h4 id="heading-why-pop-matters-for-embedded-systems">Why POP Matters for Embedded Systems</h4>
<p>First, you get flexible hardware extraction. Protocols make it easy to define interfaces for hardware components, allowing for mock implementations during testing or platform-specific variations.</p>
<p>Second, you have nice low overhead. Embedded Swift uses static dispatch for protocols, meaning there’s no runtime lookup, and calls are resolved at compile time for maximum performance.</p>
<p>Also, <code>struct</code> and <code>enum</code> types avoid heap allocations, making code more efficient and predictable in low-memory environments.</p>
<p>Now that we’ve explored how Swift’s programming model enables safer and more modular embedded code, let’s turn to another critical piece of the puzzle: memory management. Swift’s use of Automatic Reference Counting (ARC) replaces manual memory handling and offers important benefits, and tradeoffs, for embedded systems.</p>
<h2 id="heading-swift-memory-management">Swift Memory Management</h2>
<p>One of Swift’s most impactful features, especially in the context of embedded systems, is its use of Automatic Reference Counting (ARC) for memory management. Unlike C/C++, where memory must be manually allocated and freed using <code>malloc</code> and <code>free</code>, Swift automates this process while maintaining deterministic performance.</p>
<p>This automation significantly reduces the risk of common memory-related bugs like leaks, dangling pointers, or use-after-free errors, all of which are notorious in low-level C code.</p>
<h3 id="heading-how-arc-works">How ARC works</h3>
<p>Swift supports ARC not only for the Cocoa Touch API's but for all APIs, providing a streamlined approach to memory management. Unlike garbage collection systems that can cause unpredictable pauses, ARC works deterministically at compile time and runtime to manage memory.</p>
<p>ARC automatically tracks and manages the lifetime of objects in memory based on how many references point to them.</p>
<ul>
<li><p>Reference Counting: Every object has a counter that tracks how many strong references point to it.</p>
</li>
<li><p>Retain / Release: The compiler inserts <code>retain</code> and <code>release</code> calls automatically during assignment and deinitialization.</p>
</li>
<li><p>Immediate Deallocation: When the reference count reaches zero, the object is deallocated immediately.</p>
</li>
<li><p>Deterministic: Unlike garbage collectors, ARC doesn’t introduce unpredictable pauses or runtime scanning.</p>
</li>
</ul>
<p>Swift offers multiple reference types to give you precise control over memory behavior and prevent cycles:</p>
<p><strong>Strong References</strong> (default)</p>
<ul>
<li><p>Keeps the referenced object alive.</p>
</li>
<li><p>Used in most cases.</p>
</li>
</ul>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MotorController</span> </span>{
    <span class="hljs-keyword">var</span> sensor: <span class="hljs-type">SensorData?</span>  <span class="hljs-comment">// Strong reference</span>

    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">updateReading</span><span class="hljs-params">(newData: SensorData)</span></span> {
        <span class="hljs-keyword">self</span>.sensor = newData  <span class="hljs-comment">// Previous sensor data automatically deallocated</span>
    }
}
</code></pre>
<p><strong>Weak References</strong></p>
<ul>
<li><p>Used to break reference cycles (especially in two-way object relationships).</p>
</li>
<li><p>Automatically becomes <code>nil</code> when the referenced object is deallocated.</p>
</li>
</ul>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Device</span> </span>{
    <span class="hljs-keyword">var</span> controller: <span class="hljs-type">MotorController?</span>

    <span class="hljs-keyword">deinit</span> {
        <span class="hljs-built_in">print</span>(<span class="hljs-string">"Device deallocated"</span>)
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MotorController</span> </span>{
    <span class="hljs-keyword">weak</span> <span class="hljs-keyword">var</span> device: <span class="hljs-type">Device?</span>  <span class="hljs-comment">// ← Weak reference breaks the cycle</span>

    <span class="hljs-keyword">deinit</span> {
        <span class="hljs-built_in">print</span>(<span class="hljs-string">"MotorController deallocated"</span>)
    }
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">breakCycle</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">let</span> device = <span class="hljs-type">Device</span>()
    <span class="hljs-keyword">let</span> controller = <span class="hljs-type">MotorController</span>()

    device.controller = controller
    controller.device = device  <span class="hljs-comment">// ← This is now a weak reference</span>

    <span class="hljs-comment">// When this function ends, both objects are properly deallocated</span>
}

breakCycle()
<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// Device deallocated</span>
<span class="hljs-comment">// MotorController deallocated</span>
</code></pre>
<p><strong>Unowned References</strong></p>
<ul>
<li><p>Non-optional version of <code>weak</code>.</p>
</li>
<li><p>Assumes the object will never be deallocated while still in use.</p>
</li>
<li><p>More lightweight than <code>weak</code>, but unsafe if misused.</p>
</li>
</ul>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SensorSystem</span> </span>{
    <span class="hljs-keyword">unowned</span> <span class="hljs-keyword">let</span> controller: <span class="hljs-type">MotorController</span>  <span class="hljs-comment">// unowned reference</span>

    <span class="hljs-keyword">init</span>(controller: <span class="hljs-type">MotorController</span>) {
        <span class="hljs-keyword">self</span>.controller = controller
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MotorController</span> </span>{
    <span class="hljs-keyword">var</span> sensorSystem: <span class="hljs-type">SensorSystem?</span>

    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">setupSensors</span><span class="hljs-params">()</span></span> {
        sensorSystem = <span class="hljs-type">SensorSystem</span>(controller: <span class="hljs-keyword">self</span>)
    }

    <span class="hljs-keyword">deinit</span> {
        <span class="hljs-built_in">print</span>(<span class="hljs-string">"MotorController deallocated"</span>)
    }
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">testUnowned</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">let</span> controller = <span class="hljs-type">MotorController</span>()
    controller.setupSensors()
    <span class="hljs-comment">// sensorSystem deallocates before controller ends</span>
}

testUnowned()
<span class="hljs-comment">// Output: MotorController deallocated</span>
</code></pre>
<h3 id="heading-arc-overhead-in-embedded-systems">ARC Overhead in Embedded Systems</h3>
<p>While ARC provides safety benefits, it does introduce some overhead compared to manual memory management:</p>
<h4 id="heading-memory-overhead">Memory Overhead:</h4>
<p>ARC-managed class instances in Swift typically include an additional 4 or 8 bytes to store reference count metadata, depending on the system architecture, 4 bytes on 32-bit systems and 8 bytes on 64-bit systems. This metadata allows the runtime to track how many active references exist to a given object and deallocate it when no references remain. When developers use weak or unowned references, the memory footprint increases further. These references require additional data structures, such as side tables or tracking mechanisms, to manage object liveness and cleanup. In the case of weak references specifically, Swift maintains zeroing weak reference tables that automatically null out pointers once the referenced object is deallocated, ensuring memory safety.</p>
<h4 id="heading-cpu-overhead">CPU Overhead:</h4>
<p>ARC introduces some runtime overhead due to retain and release operations, which are inserted automatically during reference assignments. These operations involve incrementing or decrementing the reference count and are especially common in code that passes objects between functions or stores them in collections. To ensure thread safety, these updates are typically implemented using atomic operations, which add further instruction cycles. In complex object graphs, ARC may also engage in cycle detection and cleanup through the use of weak references to prevent memory leaks caused by strong reference cycles. While Swift's ARC provides deterministic and efficient memory management, it does so with both memory and CPU costs that developers should consider carefully, especially in performance-critical embedded systems.</p>
<h3 id="heading-type-safety-and-error-prevention">Type Safety and Error Prevention</h3>
<p>Swift's type system prevents many common errors that plague C/C++ programs:</p>
<ul>
<li><p><strong>Buffer Overflows</strong>: Swift arrays are bounds-checked, preventing buffer overflow vulnerabilities that are common in C.</p>
</li>
<li><p><strong>Null Pointer Dereferences</strong>: Swift's optional types make null pointer dereferences impossible at compile time.</p>
</li>
<li><p><strong>Use After Free</strong>: Swift's ownership model prevents use-after-free errors that can cause crashes or security vulnerabilities.</p>
</li>
</ul>
<p>Now that we’ve covered Swift's memory model and ARC behavior, let’s explore how it compares to C in terms of memory usage and instruction cycles, a crucial aspect when evaluating Embedded Swift for real-world deployment.</p>
<h2 id="heading-memory-and-instruction-cycle-comparison">Memory and Instruction Cycle Comparison</h2>
<p>Understanding the performance characteristics of Swift versus C is essential for embedded systems, where every instruction cycle and byte of memory matters. While Swift brings advantages like safety and expressiveness, these benefits come with certain trade-offs in terms of memory usage and runtime behavior that embedded developers must evaluate carefully.</p>
<h3 id="heading-memory-management">Memory Management:</h3>
<p>Swift uses Automatic Reference Counting (ARC) to manage memory. ARC tracks the number of references to each object and deallocates it when no references remain. This eliminates the need for explicit <code>free()</code> calls but introduces overhead.</p>
<p>C, in contrast, uses manual memory management. Developers allocate memory using <code>malloc</code> and release it using <code>free</code>, or rely on the stack for most short-lived data.</p>
<p>The table below provides the memory management comparison between Swift and C:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Feature</strong></td><td><strong>Swift (ARC)</strong></td><td><strong>C (Manual)</strong></td></tr>
</thead>
<tbody>
<tr>
<td>Memory strategy</td><td>Automatic reference counting</td><td>Manual with <code>malloc</code>/<code>free</code></td></tr>
<tr>
<td>Overhead per object</td><td>4–8 bytes (for ref count)</td><td>None for stack; variable for heap</td></tr>
<tr>
<td>Deallocation</td><td>Deterministic, triggered by ARC</td><td>Developer-controlled</td></tr>
<tr>
<td>Weak reference support</td><td>Requires additional metadata</td><td>Not built-in</td></tr>
<tr>
<td>Thread safety</td><td>Atomic operations in ARC</td><td>Not guaranteed</td></tr>
<tr>
<td>Layout control</td><td>Limited, compiler-managed</td><td>Full control (via structs/pointers)</td></tr>
</tbody>
</table>
</div><p>Swift ensures safety through deterministic cleanup and predictable memory usage. But this comes at the cost of added memory and CPU overhead.</p>
<p>C’s approach offers complete control over memory layout and minimal runtime cost, but increases the risk of memory leaks and fragmentation without disciplined practices.</p>
<h3 id="heading-instruction-cycle-analysis">Instruction Cycle Analysis</h3>
<p>The safety features in Swift, such as bounds checking, optional unwrapping, and ARC updates, translate into additional CPU instructions. While this can impact performance, the Swift compiler is aggressive about optimization in release builds. For example, inlining and ARC elision can remove much of the overhead in performance-critical paths.</p>
<p>C has no built-in safety checks, allowing it to generate highly efficient, predictable code. Developers can even use inline assembly for tight control over performance.</p>
<p>The table below provides the instruction cycle comparison between Swift and C:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Instruction-Level Feature</strong></td><td><strong>Swift</strong></td><td><strong>C</strong></td></tr>
</thead>
<tbody>
<tr>
<td>Reference count updates</td><td>2–4 instructions per assignment</td><td>N/A</td></tr>
<tr>
<td>Bounds checking</td><td>1–3 instructions per array access</td><td>None</td></tr>
<tr>
<td>Optional unwrapping</td><td>1–2 instructions per check</td><td>N/A</td></tr>
<tr>
<td>Method dispatch</td><td>Protocols introduce indirection</td><td>Direct calls or function pointers</td></tr>
<tr>
<td>Optimization potential</td><td>ARC elision, inlining, dead code removal</td><td>Full manual control, inline assembly</td></tr>
<tr>
<td>Predictability</td><td>High in optimized builds, with some abstraction overhead</td><td>Very high, minimal abstraction</td></tr>
</tbody>
</table>
</div><p>Although Swift inserts extra instructions for safety, much of this cost can be mitigated through compiler optimization.</p>
<p>C has no such features by default, making it ideal for applications where performance must be tightly controlled and the developer is willing to take full responsibility for safety.</p>
<h3 id="heading-instruction-count-comparison-swift-vs-c-loop-performance">Instruction Count Comparison: Swift vs C Loop Performance</h3>
<p>When evaluating Swift and C for embedded use, it's helpful to analyze instruction-level performance on basic operations, such as a loop that processes an array of floating-point numbers. This gives us a concrete sense of the computational cost of each language's safety and abstraction features.</p>
<p>Let’s consider a simple example: summing an array of <code>Float</code> values and returning the average. In Swift, the code uses a high-level <code>for-in</code> loop over an array:</p>
<p>Simple loop performance:</p>
<pre><code class="lang-swift"><span class="hljs-comment">// Swift loop with safety checks</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">processData</span><span class="hljs-params">(<span class="hljs-number">_</span> data: [Float])</span></span> -&gt; <span class="hljs-type">Float</span> {
    <span class="hljs-keyword">var</span> sum: <span class="hljs-type">Float</span> = <span class="hljs-number">0.0</span>
    <span class="hljs-keyword">for</span> value <span class="hljs-keyword">in</span> data {  <span class="hljs-comment">// Iterator with bounds checking</span>
        sum += value     <span class="hljs-comment">// Safe arithmetic</span>
    }
    <span class="hljs-keyword">return</span> sum / <span class="hljs-type">Float</span>(data.<span class="hljs-built_in">count</span>)  <span class="hljs-comment">// Safe division</span>
}
<span class="hljs-comment">// Estimated: ~8-10 instructions per iteration</span>
</code></pre>
<p>Although elegant and safe, this loop includes several safety mechanisms:</p>
<ol>
<li><p>Bounds checking on every array access</p>
</li>
<li><p>Reference counting if <code>data</code> is passed as a reference type</p>
</li>
<li><p>Overflow protection in debug mode</p>
</li>
<li><p>Optional handling or runtime checks if <code>data</code> might be empty</p>
</li>
</ol>
<p>These checks introduce runtime overhead, resulting in an estimated 8–10 instructions per iteration on most platforms (depending on optimization level and target architecture). In release builds, Swift aggressively inlines and strips redundant checks, but some level of abstraction cost remains, especially compared to raw memory access in C.</p>
<p>Now, compare that to its equivalent in C:</p>
<pre><code class="lang-c"><span class="hljs-comment">// C loop without safety checks</span>
<span class="hljs-function"><span class="hljs-keyword">float</span> <span class="hljs-title">process_data</span><span class="hljs-params">(<span class="hljs-keyword">float</span>* data, <span class="hljs-keyword">int</span> count)</span> </span>{
    <span class="hljs-keyword">float</span> sum = <span class="hljs-number">0.0f</span>;
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; count; i++) {  <span class="hljs-comment">// Direct pointer arithmetic</span>
        sum += data[i];                <span class="hljs-comment">// Direct memory access</span>
    }
    <span class="hljs-keyword">return</span> sum / count;  <span class="hljs-comment">// Direct division (no safety check)</span>
}
<span class="hljs-comment">// Estimated: ~4-5 instructions per iteration</span>
</code></pre>
<p>This version performs direct memory access with pointer arithmetic, no bounds checks, and no type safety. The C code is lower-level, with fewer runtime checks, and compiles down to just 4–5 instructions per iteration, depending on the target CPU and compiler flags. It is lean and fast, ideal for cycles-per-instruction-critical scenarios.</p>
<p>The table below shows the comparison of single loop performance between Swift and C:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Aspect</td><td>Swift</td><td>C</td></tr>
</thead>
<tbody>
<tr>
<td>Array access</td><td>Bounds-checked</td><td>Direct pointer access</td></tr>
<tr>
<td>Loop iteration</td><td>High-level iterator abstraction</td><td>Raw loop with pointer increment</td></tr>
<tr>
<td>Instruction count (per loop)</td><td>~8–10 (in debug), ~6–8 (in release)</td><td>~4–5</td></tr>
<tr>
<td>Division</td><td>Safe (avoids divide-by-zero in dev)</td><td>Direct</td></tr>
<tr>
<td>Overflow behavior</td><td>Checked in debug, unchecked in release</td><td>Unchecked</td></tr>
<tr>
<td>Readability and safety</td><td>High</td><td>Low</td></tr>
<tr>
<td>Performance</td><td>Lower (but optimizable)</td><td>Higher (manual)</td></tr>
</tbody>
</table>
</div><p>Now that we’ve compared Swift and C in terms of memory and cycle costs, let’s move into the practical side: how to set up Embedded Swift on an STM32 platform and get started with real-world development.</p>
<h2 id="heading-how-to-setup-embedded-swift">How to Setup Embedded Swift</h2>
<p>In this section, we'll walk through how to configure and use Embedded Swift for development on STM32 microcontrollers. STM32 is a popular family of ARM Cortex-M–based microcontrollers, commonly used in industrial, consumer, and IoT applications.</p>
<h3 id="heading-prerequisites-1">Prerequisites</h3>
<p><strong>Required Software:</strong></p>
<ul>
<li><p>Swift Development Snapshot (includes the Embedded Swift toolchain)</p>
</li>
<li><p>Swiftly - Easiest way to manage and install swift toolchains</p>
</li>
<li><p>Swiftc - Swift Compiler command-line tool</p>
</li>
<li><p>Python3 - Required to run scripts to convert Mach-O to binary files</p>
</li>
<li><p>Git (to clone sample repositories) like <a target="_blank" href="https://github.com/swiftlang/swift-embedded-examples">https://github.com/swiftlang/swift-embedded-examples</a></p>
</li>
<li><p>A Unix-like development environment (macOS is currently best supported)</p>
</li>
</ul>
<p><strong>Target Hardware:</strong> This guide focuses on STM32 microcontrollers, which are widely used in embedded applications and have excellent community support.</p>
<p>This guide walks you through the full setup process, from installing the required Swift toolchain to flashing the final binary onto your board. We’ll begin by installing the Swift Development Snapshot using Swiftly, a simple command-line utility for managing Swift toolchains. From there, we’ll configure the build system, set up the correct board variant, customize the build script, and compile the Swift and C source code into a binary. Finally, we’ll flash the firmware onto the STM32 using standard tools</p>
<h3 id="heading-install-swift-development-snapshot">Install Swift Development Snapshot</h3>
<p>The easiest way to install and manage Embedded Swift toolchains is by using the swiftly tool, which simplifies downloading and using Swift snapshots.</p>
<h4 id="heading-macos-installation">macOS Installation:</h4>
<p>The below steps will help install the Swift embedded toolchain:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Using Swiftly (Recommended)</span>
curl -O https://download.swift.org/swiftly/darwin/swiftly.pkg
installer -pkg swiftly.pkg -target CurrentUserHomeDirectory
~/.swiftly/bin/swiftly init --quiet-shell-followup
<span class="hljs-built_in">source</span> <span class="hljs-string">"<span class="hljs-variable">${SWIFTLY_HOME_DIR:-<span class="hljs-variable">$HOME</span>/.swiftly}</span>/env.sh"</span>

<span class="hljs-comment"># Install and use development snapshot</span>
swiftly install main-snapshot
swiftly use main-snapshot

<span class="hljs-comment"># Verify installation</span>
swift --version
</code></pre>
<p>You can clone this Github example repository:</p>
<pre><code class="lang-bash">git <span class="hljs-built_in">clone</span> https://github.com/swiftlang/swift-embedded-examples.git 
<span class="hljs-built_in">cd</span> swift-embedded-examples/projects/stm32-blink
</code></pre>
<p>The stm32-blink contains:</p>
<ul>
<li><p>Swift code that toggles GPIOs</p>
</li>
<li><p>A C startup file with vector table</p>
</li>
<li><p>A build.sh script that uses swiftc, clang, and a custom linker setup</p>
</li>
</ul>
<h3 id="heading-setup-the-stm32-board">Setup the STM32 Board</h3>
<p>Tell the build script which STM32 board is being used:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">export</span> STM_BOARD=STM32F746G_DISCOVERY
</code></pre>
<p>You can add your own board variant by defining the appropriate memory map and compiler flags in the script.</p>
<h3 id="heading-modify-buildsh-optional">Modify build.sh (Optional)</h3>
<p>Ensure the script correctly locates the following:</p>
<ul>
<li><p>swiftc: should point to the toolchain you installed with Swiftly</p>
</li>
<li><p>clang: can be macOS’s default Clang</p>
</li>
<li><p>libBuiltin.a, crt0.s, and macho2bin.py: used to provide minimal runtime support and convert output to flashable binaries</p>
</li>
</ul>
<p>If needed, update these paths:</p>
<pre><code class="lang-bash">SWIFT_EXEC=<span class="hljs-variable">${SWIFT_EXEC:-$(swiftly which swiftc)}</span>
CLANG_EXEC=<span class="hljs-variable">${CLANG_EXEC:-$(xcrun -f clang)}</span>
PYTHON_EXEC=<span class="hljs-variable">${PYTHON_EXEC:-$(which python3)}</span>
</code></pre>
<p>Ensure the linker flags match your target’s flash and RAM sizes.</p>
<h3 id="heading-build-and-flash-the-project">Build and Flash the Project:</h3>
<p>Run:</p>
<pre><code class="lang-bash">./build.sh
</code></pre>
<p>This compiles Swift and C code, links them, and produces a blink.bin file.</p>
<p>If successful, you’ll see:</p>
<pre><code class="lang-bash">.build/blink.bin  <span class="hljs-comment"># ready to flash Step 6: Flash the Firmware to STM32</span>
</code></pre>
<p>Use ST-Link tools or openocd to flash your board. Example using st-flash:</p>
<pre><code class="lang-bash">brew install stlink
st-flash write .build/blink.bin 0x8000000
</code></pre>
<p>You should now see an LED blinking.</p>
<p><a target="_blank" href="https://docs.swift.org/embedded/documentation/embedded/stm32baremetalguide">Here’s</a> a more detailed step by step approach to writing a bare metal code on STM32. For comprehensive installation guides covering other platforms (Raspberry Pi Pico, ESP32, nRF52), detailed IDE configuration, troubleshooting, and advanced examples, you can check out the official documentation:</p>
<ul>
<li><p>Complete Setup Guide: <a target="_blank" href="https://docs.swift.org/embedded/documentation/embedded/installembeddedswift/">Install Embedded Swift</a></p>
</li>
<li><p>Platform Examples: <a target="_blank" href="https://github.com/apple/swift-embedded-examples">Swift Embedded Examples Repository</a></p>
</li>
<li><p>Getting Started Tutorial: <a target="_blank" href="https://docs.swift.org/embedded/documentation/embedded">Embedded Swift on Microcontrollers</a></p>
</li>
</ul>
<p>Now that we’ve set up Embedded Swift and explored how to build and run an example project, let’s look at a critical real-world scenario: interfacing Swift with low-level C drivers.</p>
<h2 id="heading-c-swift-linkages">C-Swift Linkages</h2>
<p>In many embedded projects, low-level hardware drivers are written in C because of its close-to-metal control and widespread ecosystem support. Embedded Swift supports seamless interoperability with C, which lets you reuse existing C libraries and drivers, write hardware control logic in C, and implement higher-level application logic in Swift.</p>
<p>This hybrid model lets you combine Swift’s safety and productivity with C’s hardware-level control, with no runtime overhead or object translation.</p>
<p>Let’s walk through an example where a low-level sensor driver is implemented in C and the application logic is written in Swift.</p>
<h3 id="heading-c-header-file-sensordriverh">C Header File (sensor_driver.h):</h3>
<p>This C header file defines the public interface for a low-level sensor driver. It includes standard fixed-width integer types and declares four functions:</p>
<ul>
<li><p>sensor_init(): Initializes the hardware sensor</p>
</li>
<li><p>sensor_read_temperature() and sensor_read_humidity(): Read raw sensor values</p>
</li>
<li><p>sensor_delay_ms(): Delays execution for a given number of milliseconds</p>
</li>
</ul>
<p>This interface acts as a bridge between Swift and C. Swift will link to these functions by name, no wrappers or bindings required.</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">ifndef</span> SENSOR_DRIVER_H</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> SENSOR_DRIVER_H</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdint.h&gt;</span></span>

<span class="hljs-comment">// Low-level sensor driver functions</span>
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">sensor_init</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span></span>;
<span class="hljs-function"><span class="hljs-keyword">uint32_t</span> <span class="hljs-title">sensor_read_temperature</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span></span>;
<span class="hljs-function"><span class="hljs-keyword">uint32_t</span> <span class="hljs-title">sensor_read_humidity</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span></span>;
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">sensor_delay_ms</span><span class="hljs-params">(<span class="hljs-keyword">uint32_t</span> milliseconds)</span></span>;

<span class="hljs-meta">#<span class="hljs-meta-keyword">endif</span></span>
</code></pre>
<h3 id="heading-c-implementation-sensordriverc">C Implementation (sensor_driver.c):</h3>
<p>This implementation assumes the sensor is memory-mapped at a fixed address (<code>0x40001000</code>). Each register, temperature, humidity, and control, is accessed by offset from that base address.</p>
<p>The <code>sensor_init</code>() function writes <code>0x01</code> to the control register, presumably enabling or starting the sensor hardware.</p>
<p>The <code>sensor_read_temperature()</code> method and <code>sensor_read_humidity()</code> method reads from memory-mapped registers and return the raw ADC values from the sensor.</p>
<p>The <code>sensor_delay_ms()</code> method performs a simple busy-wait loop using nop (no-operation) instructions to approximate a delay. This is suitable for short, coarse-grained delays in bare-metal contexts.</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"sensor_driver.h"</span></span>

<span class="hljs-comment">// Hardware register addresses</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> SENSOR_BASE_ADDR    0x40001000</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> TEMP_REG_OFFSET     0x00</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> HUMIDITY_REG_OFFSET 0x04</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> CONTROL_REG_OFFSET  0x08</span>

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">sensor_init</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
    <span class="hljs-comment">// Initialize sensor hardware</span>
    <span class="hljs-keyword">volatile</span> <span class="hljs-keyword">uint32_t</span>* control_reg = (<span class="hljs-keyword">volatile</span> <span class="hljs-keyword">uint32_t</span>*)(SENSOR_BASE_ADDR + CONTROL_REG_OFFSET);
    *control_reg = <span class="hljs-number">0x01</span>; <span class="hljs-comment">// Enable sensor</span>
}

<span class="hljs-function"><span class="hljs-keyword">uint32_t</span> <span class="hljs-title">sensor_read_temperature</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
    <span class="hljs-keyword">volatile</span> <span class="hljs-keyword">uint32_t</span>* temp_reg = (<span class="hljs-keyword">volatile</span> <span class="hljs-keyword">uint32_t</span>*)(SENSOR_BASE_ADDR + TEMP_REG_OFFSET);
    <span class="hljs-keyword">return</span> *temp_reg;
}

<span class="hljs-function"><span class="hljs-keyword">uint32_t</span> <span class="hljs-title">sensor_read_humidity</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
    <span class="hljs-keyword">volatile</span> <span class="hljs-keyword">uint32_t</span>* humidity_reg = (<span class="hljs-keyword">volatile</span> <span class="hljs-keyword">uint32_t</span>*)(SENSOR_BASE_ADDR + HUMIDITY_REG_OFFSET);
    <span class="hljs-keyword">return</span> *humidity_reg;
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">sensor_delay_ms</span><span class="hljs-params">(<span class="hljs-keyword">uint32_t</span> milliseconds)</span> </span>{
    <span class="hljs-comment">// Simple delay implementation</span>
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">uint32_t</span> i = <span class="hljs-number">0</span>; i &lt; milliseconds * <span class="hljs-number">1000</span>; i++) {
        __asm__(<span class="hljs-string">"nop"</span>);
    }
}
</code></pre>
<h3 id="heading-swift-code-using-c-driver">Swift Code Using C Driver:</h3>
<p>To use these C functions from Swift, you declare them using <code>@_silgen_name</code>, which tells the Swift compiler to link directly to these symbol names at runtime.</p>
<p>The <code>SensorController</code> class encapsulates sensor-related logic. In its <code>init()</code> method, it calls the <code>sensor_init()</code> function defined in C to initialize the sensor hardware.</p>
<p>The <code>readSensors()</code> method reads the raw values from the C driver, converts them into human-readable units using helper functions, stores them internally, and returns the processed values.</p>
<p>The <code>convertTemperature()</code> and <code>convertHumidity()</code> conversion methods apply a basic linear formula to turn raw ADC values into temperature in Celsius and humidity in percentage, respectively. These formulas would be based on the specific sensor’s datasheet.</p>
<p>The <code>checkThresholds()</code> method applies simple threshold logic, a good example of where Swift’s readability and type safety shine. You could easily expand this logic to include error bounds, state machines, or alerts.</p>
<pre><code class="lang-swift"><span class="hljs-comment">// Import C driver functions</span>

<span class="hljs-comment">/*
These declarations match the C function signatures exactly. 
They allow Swift to invoke the C functions as if they were native Swift functions 
— with zero overhead.
*/</span>
@_silgen_name(<span class="hljs-string">"sensor_init"</span>)
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">sensor_init</span><span class="hljs-params">()</span></span>

@_silgen_name(<span class="hljs-string">"sensor_read_temperature"</span>)
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">sensor_read_temperature</span><span class="hljs-params">()</span></span> -&gt; <span class="hljs-type">UInt32</span>

@_silgen_name(<span class="hljs-string">"sensor_read_humidity"</span>)
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">sensor_read_humidity</span><span class="hljs-params">()</span></span> -&gt; <span class="hljs-type">UInt32</span>

@_silgen_name(<span class="hljs-string">"sensor_delay_ms"</span>)
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">sensor_delay_ms</span><span class="hljs-params">(<span class="hljs-number">_</span> ms: UInt32)</span></span>

<span class="hljs-comment">// Swift sensor controller using C driver</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SensorController</span> </span>{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">var</span> lastTemperature: <span class="hljs-type">Float</span> = <span class="hljs-number">0.0</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">var</span> lastHumidity: <span class="hljs-type">Float</span> = <span class="hljs-number">0.0</span>

    <span class="hljs-keyword">init</span>() {
        <span class="hljs-comment">// Initialize the C driver</span>
        sensor_init()
    }

    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">readSensors</span><span class="hljs-params">()</span></span> -&gt; (temperature: <span class="hljs-type">Float</span>, humidity: <span class="hljs-type">Float</span>) {
        <span class="hljs-comment">// Read raw values from C driver</span>
        <span class="hljs-keyword">let</span> rawTemp = sensor_read_temperature()
        <span class="hljs-keyword">let</span> rawHumidity = sensor_read_humidity()

        <span class="hljs-comment">// Convert raw values to meaningful units in Swift</span>
        <span class="hljs-keyword">let</span> temperature = convertTemperature(rawValue: rawTemp)
        <span class="hljs-keyword">let</span> humidity = convertHumidity(rawValue: rawHumidity)

        <span class="hljs-comment">// Store for comparison</span>
        lastTemperature = temperature
        lastHumidity = humidity

        <span class="hljs-keyword">return</span> (temperature: temperature, humidity: humidity)
    }

    <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">convertTemperature</span><span class="hljs-params">(rawValue: UInt32)</span></span> -&gt; <span class="hljs-type">Float</span> {
        <span class="hljs-comment">// Convert raw ADC value to Celsius</span>
        <span class="hljs-keyword">return</span> (<span class="hljs-type">Float</span>(rawValue) * <span class="hljs-number">3.3</span> / <span class="hljs-number">4095.0</span> - <span class="hljs-number">0.5</span>) * <span class="hljs-number">100.0</span>
    }

    <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">convertHumidity</span><span class="hljs-params">(rawValue: UInt32)</span></span> -&gt; <span class="hljs-type">Float</span> {
        <span class="hljs-comment">// Convert raw ADC value to percentage</span>
        <span class="hljs-keyword">return</span> <span class="hljs-type">Float</span>(rawValue) * <span class="hljs-number">100.0</span> / <span class="hljs-number">4095.0</span>
    }

    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">checkThresholds</span><span class="hljs-params">()</span></span> -&gt; <span class="hljs-type">Bool</span> {
        <span class="hljs-comment">// Swift logic for threshold checking</span>
        <span class="hljs-keyword">let</span> tempThreshold: <span class="hljs-type">Float</span> = <span class="hljs-number">25.0</span>
        <span class="hljs-keyword">let</span> humidityThreshold: <span class="hljs-type">Float</span> = <span class="hljs-number">60.0</span>

        <span class="hljs-keyword">return</span> lastTemperature &gt; tempThreshold || lastHumidity &gt; humidityThreshold
    }
}

<span class="hljs-comment">// Main application loop</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> -&gt; <span class="hljs-type">Never</span> {
    <span class="hljs-keyword">let</span> sensorController = <span class="hljs-type">SensorController</span>()

    <span class="hljs-keyword">while</span> <span class="hljs-literal">true</span> {
        <span class="hljs-comment">// Read sensors using Swift controller with C driver</span>
        <span class="hljs-keyword">let</span> readings = sensorController.readSensors()

        <span class="hljs-comment">// Process data with Swift's type safety and expressiveness</span>
        <span class="hljs-keyword">if</span> sensorController.checkThresholds() {
            <span class="hljs-built_in">print</span>(<span class="hljs-string">"Warning: Temperature: \(readings.temperature)°C, Humidity: \(readings.humidity)%"</span>)
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-built_in">print</span>(<span class="hljs-string">"Normal: Temperature: \(readings.temperature)°C, Humidity: \(readings.humidity)%"</span>)
        }

        <span class="hljs-comment">// Delay using C driver function</span>
        sensor_delay_ms(<span class="hljs-number">1000</span>) <span class="hljs-comment">// 1 second delay</span>
    }
}
</code></pre>
<p>The <code>func main()</code> is the main event loop standard for embedded systems. It creates the sensor controller, reads sensor data in a loop, checks thresholds, and prints results accordingly. The loop includes a delay (via the C driver) to avoid hammering the sensor continuously.</p>
<p>In an actual embedded context, instead of using <code>print()</code>, you might blink an LED, send UART messages, or log data to memory.</p>
<p>With Embedded Swift and C now working together, let’s explore what lies ahead. The next section outlines ongoing improvements, emerging use cases, and research directions that are shaping the future of Embedded Swift.</p>
<h2 id="heading-future-work">Future Work</h2>
<p>Embedded Swift is still a young but rapidly evolving technology. Its modern language features, type safety, and performance make it an attractive option for embedded development, and ongoing work is expanding its capabilities, reach, and ecosystem.</p>
<h3 id="heading-ongoing-improvements">Ongoing Improvements</h3>
<p><strong>Compiler Optimizations</strong>: The Swift compiler team is actively improving code generation for embedded targets, including:</p>
<ul>
<li><p>Reducing binary size</p>
</li>
<li><p>Minimizing ARC overhead</p>
</li>
<li><p>Improving static dispatch performance</p>
</li>
</ul>
<p><strong>Hardware Support</strong>: Embedded Swift can target a wide variety of ARM and RISC-V microcontrollers, which are popular for building industrial applications. Support for additional architectures is being developed.</p>
<p><strong>Tooling Enhancements</strong>: Tooling support for Embedded Swift is still evolving, but several community-driven and open-source efforts are making development more accessible:</p>
<ul>
<li><p><strong>Build Systems</strong>: The Swift Embedded Working Group provides example projects that adapt Swift Package Manager (SwiftPM) for cross-compilation. Custom linker scripts and build helpers are available for platforms like STM32 and nRF52.</p>
</li>
<li><p><strong>Debugging Support</strong>: Developers can debug Embedded Swift programs using existing tools like GDB or OpenOCD, provided the build includes appropriate debug symbols. While not yet officially streamlined, this approach enables step-through debugging on real hardware.</p>
</li>
<li><p><strong>IDE Integration</strong>: There is no official IDE support yet, but some developers use VSCode with Swift syntax highlighting and external build tasks. These setups are still manual but serve as early prototypes for embedded workflows.</p>
</li>
</ul>
<h3 id="heading-emerging-use-cases">Emerging Use Cases</h3>
<p>There are a number of emerging use cases for embedded Swift. For example, Swift’s memory safety, type guarantees, and protocol-oriented design make it ideal for secure and scalable IoT devices, especially where firmware bugs could affect user safety or privacy.</p>
<p>The automotive sector is also exploring Swift for infotainment systems, driver assistance features, and safety-critical logic (where deterministic execution and safety matter).</p>
<p>Swift’s expressive syntax and compile-time safety make it suitable for industrial automation – think real-time control loops, sensor fusion systems, and edge devices in smart manufacturing.</p>
<p>It’s also useful for medical devices, as it aligns well with strict medical regulations around memory safety, type guarantees, and predictable resource usage.</p>
<h3 id="heading-community-and-ecosystem">Community and Ecosystem</h3>
<h4 id="heading-open-source-projects">Open Source Projects</h4>
<p>The Swift Embedded working group maintains <a target="_blank" href="https://github.com/swiftlang/swift-embedded-examples">example repositories</a> showcasing how to use Embedded Swift on microcontrollers such as STM32, nRF52, and ESP32. Early-stage libraries for UART, GPIO, and basic peripherals are emerging, though the ecosystem is still young compared to C or Rust.</p>
<h4 id="heading-learning-resources">Learning Resources</h4>
<p>While <a target="_blank" href="https://docs.swift.org/embedded/documentation/embedded">Embedded Swift</a> is not yet widely taught in formal curricula, community tutorials and exploratory projects (for example, Swift for Arduino) are lowering the barrier for hobbyists and independent learners. As tooling matures, educational adoption is likely to follow.</p>
<h4 id="heading-industry-interest">Industry Interest</h4>
<p>Embedded Swift is beginning to draw attention from developers and companies looking for safer, more maintainable alternatives to C. Although large-scale adoption remains limited, use cases like rapid prototyping, IoT development, and internal experimentation are gaining traction.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Embedded Swift represents a major step forward in embedded programming. By combining the power and safety of Swift with the low-level control needed for microcontrollers, it offers an exciting alternative to traditional C and C++ development.</p>
<p>While C will remain essential for hardware-level programming and performance-critical paths, Swift brings compelling advantages to many embedded scenarios:</p>
<ul>
<li><p><strong>Memory safety</strong>: Swift eliminates entire categories of bugs such as buffer overflows, use-after-free, and null pointer dereferencing.</p>
</li>
<li><p><strong>Type safety</strong>: Many logic errors are caught at compile time, long before they can cause runtime failures.</p>
</li>
<li><p><strong>Modern language features</strong>: Developers can use functional paradigms, generics, and protocol-oriented design even in embedded code.</p>
</li>
<li><p><strong>C interoperability</strong>: Swift works seamlessly with existing C libraries, allowing gradual adoption without rewriting low-level drivers.</p>
</li>
<li><p><strong>Developer productivity</strong>: Clear syntax, automatic memory management, and strong tooling lead to faster development and easier maintenance.</p>
</li>
</ul>
<p>Government and regulatory bodies are increasingly encouraging or mandating the use of memory-safe programming languages to reduce vulnerabilities in critical software systems. For example:</p>
<ul>
<li><p>In 2022, the <a target="_blank" href="https://media.defense.gov/2025/Jun/23/2003742198/-1/-1/0/CSI_MEMORY_SAFE_LANGUAGES_REDUCING_VULNERABILITIES_IN_MODERN_SOFTWARE_DEVELOPMENT.PDF"><strong>U.S. National Security Agency (NSA)</strong></a> recommended moving away from unsafe languages like C/C++ for new software projects, promoting memory-safe alternatives.</p>
</li>
<li><p>In June 2025, the NSA and CISA released a joint Cybersecurity Information Sheet titled “<a target="_blank" href="https://www.nsa.gov/Press-Room/Press-Releases-Statements/Press-Release-View/Article/4223298/nsa-and-cisa-release-csi-highlighting-importance-of-memory-safe-languages-in-so/">Memory Safe Languages: Reducing Vulnerabilities in Modern Software Development</a>”, which emphasized that memory safety flaws remain a persistent risk, and organizations should develop strategies to adopt memory-safe programming languages in new systems.</p>
</li>
<li><p>The <a target="_blank" href="https://www.trust-in-soft.com/resources/blogs/memory-safety-is-key-the-shift-in-u.s.-cyber-standards"><strong>U.S. Cybersecurity and Infrastructure Security Agency (CISA)</strong></a> and <a target="_blank" href="https://nvlpubs.nist.gov/nistpubs/specialpublications/nist.sp.800-218.pdf"><strong>NIST</strong></a> have echoed similar guidance in the context of national cybersecurity.</p>
</li>
</ul>
<p>While these documents do not mention Swift explicitly, Swift's strong type system, ARC-based memory model, and compile-time safety guarantees align closely with the goals outlined in these recommendations. As such, it offers a practical, developer-friendly path toward safer embedded development.</p>
<p>Swift may not be the right fit for every embedded system. In applications where every byte of memory or instruction cycle is critical, real-time guarantees are hard requirements, or toolchain maturity is essential (for example, RTOS integration, static analyzers), C or Rust may still be preferred.</p>
<p>But in many modern embedded applications, especially those involving rapid prototyping, fast product iteration, safety-critical or maintainable firmware, and interoperability with existing C codebases, Swift offers a highly productive and safe development experience.</p>
<p>Embedded Swift is still maturing, but its momentum is undeniable. With ongoing compiler work, community-driven examples, and growing interest from developers, it’s poised to play a major role in the future of embedded systems.</p>
<p>Whether you're building an IoT device, a piece of industrial equipment, or a proof-of-concept wearable, Swift can help you write safer, more expressive firmware, without giving up performance or control.</p>
<p>Swift can be especially powerful during the prototyping phase, when the primary goal is to validate functionality quickly and safely. And with its increasing support for multiple hardware platforms, it offers a strong foundation for bringing modern software development practices to the embedded world.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Debug and Prevent Buffer Overflows in Embedded Systems ]]>
                </title>
                <description>
                    <![CDATA[ Buffer overflows are one of the most serious software bugs, especially in embedded systems, where hardware limitations and real-time execution make them hard to detect and fix. A buffer overflow happens when a program writes more data into a buffer t... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-debug-and-prevent-buffer-overflows-in-embedded-systems/</link>
                <guid isPermaLink="false">67d84f228d156200bc7d3d8c</guid>
                
                    <category>
                        <![CDATA[ embedded systems ]]>
                    </category>
                
                    <category>
                        <![CDATA[ embedded ]]>
                    </category>
                
                    <category>
                        <![CDATA[ memory-management ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Buffer Overfow ]]>
                    </category>
                
                    <category>
                        <![CDATA[ debugging ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Firmware Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Security ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Code Quality ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Software Engineering ]]>
                    </category>
                
                    <category>
                        <![CDATA[ learn to code ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Programming basics ]]>
                    </category>
                
                    <category>
                        <![CDATA[ C ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Coding Best Practices ]]>
                    </category>
                
                    <category>
                        <![CDATA[ clean code ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Soham Banerjee ]]>
                </dc:creator>
                <pubDate>Mon, 17 Mar 2025 16:34:42 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1742229245130/858b21cc-443e-43ee-82ce-091438f6c5c0.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Buffer overflows are one of the most serious software bugs, especially in embedded systems, where hardware limitations and real-time execution make them hard to detect and fix.</p>
<p>A buffer overflow happens when a program writes more data into a buffer than it was allocated, leading to memory corruption, crashes, or even security vulnerabilities. A buffer corruption occurs when unintended modifications overwrite unread data or modify memory in unexpected ways.</p>
<p>In safety-critical systems like cars, medical devices, and spacecraft, buffer overflows can cause life-threatening failures. Unlike simple software bugs, buffer overflows are unpredictable and depend on the state of the system, making them difficult to diagnose and debug.</p>
<p>To prevent these issues, it's important to understand how buffer overflows and corruptions occur, and how to detect and fix them.</p>
<h2 id="heading-article-scope">Article Scope</h2>
<p>In this article, you will learn:</p>
<ol>
<li><p>What buffers, buffer overflows, and corruptions are. I’ll give you a beginner-friendly explanation with real-world examples.</p>
</li>
<li><p>How to debug buffer overflows. You’ll learn how to use tools like GDB, LLDB, and memory maps to find memory corruption.</p>
</li>
<li><p>How to prevent buffer overflows. We’ll cover some best practices like input validation, safe memory handling, and defensive programming.</p>
</li>
</ol>
<p>I’ll also show you some hands-on code examples – simple C programs that demonstrate buffer overflow issues and how to fix them.</p>
<p>What this article doesn’t cover:</p>
<ol>
<li><p>Security exploits and hacking techniques. We’ll focus on preventing accidental overflows, not hacking-related buffer overflows.</p>
</li>
<li><p>Operating system-specific issues. This guide is for embedded systems, not general-purpose computers or servers.</p>
</li>
<li><p>Advanced RTOS memory management. While we discuss interrupt-driven overflows, we won’t dive deep into real-time operating system (RTOS) concepts.</p>
</li>
</ol>
<p>Now that you know what this article covers (and what it doesn’t), let’s go over the skills that will help you get the most out of it.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>This article is designed for developers who have some experience with C programming and want to understand how to debug and prevent buffer overflows in embedded systems. Still, beginners can follow along, as I’ll explain key concepts in a clear and structured way.</p>
<p>Before reading, it helps if you know:</p>
<ol>
<li><p>Basic C programming.</p>
</li>
<li><p>How memory works – the difference between stack, heap, and global variables.</p>
</li>
<li><p>Basic debugging concepts – if you’ve used a debugger like GDB or LLDB, that’s a plus, but not required.</p>
</li>
<li><p>What embedded systems are – a basic idea of how microcontrollers store and manage memory.</p>
</li>
</ol>
<p>Even if you’re not familiar with these topics, this guide will walk you through them in an easy-to-understand way.</p>
<p>Before you dive into buffer overflows, debugging, and prevention, let’s take a step back and understand what a buffer is and why it’s important in embedded systems. Buffers play a crucial role in managing data flow between hardware and software but when handled incorrectly, they can lead to serious software failures.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-a-buffer-and-how-does-it-work">What is a Buffer, and How Does it Work?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-a-buffer-overflow">What is a Buffer Overflow?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-common-causes-of-buffer-overflows-and-corruption">Common Causes of Buffer Overflows and Corruption</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-consequences-of-buffer-overflows">Consequences of Buffer Overflows</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-debug-buffer-overflows">How to Debug Buffer Overflows</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-prevent-buffer-overflows">How to Prevent Buffer Overflows</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-what-is-a-buffer-and-how-does-it-work">What is a Buffer, and How Does it Work?</h2>
<p>A buffer is a contiguous block of memory used to temporarily store data before it is processed. Buffers are commonly used in two scenarios:</p>
<ol>
<li><p>Data accumulation: When the system needs to collect a certain amount of data before processing.</p>
</li>
<li><p>Rate matching: When the data producer generates data faster than the data consumer can process it.</p>
</li>
</ol>
<p>Buffers are typically implemented as arrays in C, where elements are indexed from 0 to N-1 (where N is the buffer size).</p>
<p>Let’s look at an example of a buffer in a sensor system.</p>
<p>Consider a system with a sensor task that generates data at 400 Hz (400 samples per second or 1 sample every 2.5 ms). But the data processor (consumer) operates at only 100 Hz (100 samples per second or 1 sample every 10 ms). Since the consumer task is slower than the producer, we need a buffer to store incoming data until it is processed.</p>
<p>To determine the buffer size, we calculate:</p>
<p>Buffer Size = Time to consume 1 sample / Time to generate 1 sample = 10 ms/ 2.5 ms = 4</p>
<p>This means the buffer must hold at least 4 samples at a time to avoid data loss.</p>
<p>Once the buffer reaches capacity, there are several strategies to decide which data gets passed to the consumer task:</p>
<ol>
<li><p>Max/min sampling: Use the maximum or minimum value in the buffer.</p>
</li>
<li><p>Averaging: Compute the average of all values in the buffer.</p>
</li>
<li><p>Random access: Pick a sample from a specific location (for example, the most recent or the first).</p>
</li>
</ol>
<p>In real-world applications, it’s beneficial to use circular buffers or double buffering to prevent data corruption.</p>
<ul>
<li><p>Circular buffer approach: A circular buffer (also called a ring buffer) continuously wraps around when it reaches the end, ensuring old data is overwritten safely without exceeding memory boundaries. The buffer size should be multiplied by 2 (4 × 2 = 8) to hold 8 samples. This allows the consumer task to process 4 samples while the next 4 samples are being filled, preventing data overwrites.</p>
</li>
<li><p>Double buffer approach: Double buffering is useful when data loss is unacceptable. It allows continuous data capture while the processor is busy handling previous data. A second buffer of the same size is added. When the first buffer is full, the write pointer switches to the second buffer, allowing the consumer task to process data from the first buffer while the second buffer is being filled. This prevents data overwrites and ensures a continuous data flow.</p>
</li>
</ul>
<p>Buffers help manage data efficiently, but what happens when they are mismanaged? This is where buffer overflows and corruptions come into play.</p>
<h2 id="heading-what-is-a-buffer-overflow">What is a Buffer Overflow?</h2>
<p>A buffer overflow occurs when a program writes more data into a buffer than it was allocated, causing unintended memory corruption. This can lead to unpredictable behavior, ranging from minor bugs to critical system failures.</p>
<p>To understand buffer overflow, let's use a simple analogy. Imagine a jug with a tap near the bottom. The jug represents a buffer, while the tap controls how much liquid (data) is consumed.</p>
<p>The jug is designed to hold a fixed amount of liquid. As long as water flows into the jug at the same rate or slower than it flows out, everything works fine. But if water flows in faster than it flows out, the jug will eventually overflow.</p>
<p>Similarly, in software, if data enters a buffer faster than it is processed, it exceeds the allocated memory space, causing a buffer overflow. In the case of a circular buffer, this can cause the write pointer to wrap around and overwrite unread data, leading to buffer corruption.</p>
<h3 id="heading-buffer-overflows-in-software">Buffer Overflows in Software</h3>
<p>Unlike the jug, where water simply spills over, a buffer overflow in software overwrites adjacent memory locations. This can cause a variety of hard-to-diagnose issues, including:</p>
<ol>
<li><p>Corrupting other data stored nearby.</p>
</li>
<li><p>Altering program execution, leading to crashes.</p>
</li>
<li><p>Security vulnerabilities, where attackers exploit overflows to inject malicious code.</p>
</li>
</ol>
<p>When a buffer overflow occurs, data can overwrite variables, function pointers, or even return addresses, depending on where the buffer is allocated.</p>
<p>Buffer overflows can occur in different memory regions:</p>
<ol>
<li><p>Buffer overflows in global/static memory (.bss / .data sections)</p>
<ul>
<li><p>These occur when global or static variables exceed their allocated size.</p>
</li>
<li><p>The overflow can corrupt adjacent variables, leading to unexpected behavior in other modules.</p>
</li>
<li><p>Debugging is easier because memory addresses are fixed at compile time unless the compiler optimizes them. Map files provide a memory layout of variables during the compilation and linking.</p>
</li>
</ul>
</li>
<li><p>Stack-based buffer overflow (more predictable, easier to debug):</p>
<ul>
<li><p>Happens when a buffer is allocated in the stack (for example, local variables inside functions).</p>
</li>
<li><p>Overflowing the stack can affect adjacent local variables or return addresses, potentially crashing the program.</p>
</li>
<li><p>In embedded systems with small stack sizes, this often leads to a crash or execution of unintended code.</p>
</li>
</ul>
</li>
<li><p>Heap-based buffer overflow (harder to debug):</p>
<ul>
<li><p>Happens when a buffer is dynamically allocated in the heap (for example, using malloc() in C).</p>
</li>
<li><p>Overflowing a heap buffer can corrupt adjacent dynamically allocated objects or heap management structures.</p>
</li>
<li><p>Debugging is harder because heap memory is allocated dynamically at runtime, causing memory locations to vary.</p>
</li>
</ul>
</li>
</ol>
<h4 id="heading-buffer-overflow-vs-buffer-corruption">Buffer Overflow vs Buffer Corruption</h4>
<p>Buffer overflow and buffer corruption are of course related, but refer to different situations.</p>
<p>A buffer overflow happens when data is written beyond the allocated buffer size, leading to memory corruption, unpredictable behavior, or system crashes.</p>
<p>A buffer corruption happens when unintended data modifications result in unexpected software failures, even if the write remains within buffer boundaries.</p>
<p>Both issues typically result from poor write pointer management, lack of boundary checks, and unexpected system behavior.</p>
<p>Now that we've covered what a buffer overflow is and how it can overwrite memory, let’s take a closer look at how these issues affect embedded systems.</p>
<p>In the next section, we’ll explore how buffer overflows and corruption happen in real-world embedded systems and break down common causes, including pointer mismanagement and boundary violations.</p>
<h2 id="heading-common-causes-of-buffer-overflows-and-corruption">Common Causes of Buffer Overflows and Corruption</h2>
<p>Embedded systems use buffers to store data from sensors, communication interfaces (like UART (Universal Asynchronous Receiver-Transmitter), SPI (Serial Peripheral Interface), I2C (Inter-integrated Circuit), and real-time tasks. These buffers are often statically allocated to avoid memory fragmentation, and many implementations use circular (ring) buffers to efficiently handle continuous data streams.</p>
<p>Here are three common scenarios where buffer overflows or corruptions occur in embedded systems:</p>
<h3 id="heading-writing-data-larger-than-the-available-space">Writing Data Larger Than the Available Space</h3>
<p><strong>Issue</strong>: The software writes incoming data to the buffer without checking if there is enough space.</p>
<p><strong>Example</strong>: Imagine a 100-byte buffer to store sensor data. The buffer receives variable-sized packets. If an incoming packet is larger than the remaining space, it will overwrite adjacent memory, leading to corruption.</p>
<p>So why does this happen?</p>
<ul>
<li><p>Some embedded designs increment the write pointer after copying data, making it too late to prevent overflow.</p>
</li>
<li><p>Many low-level memory functions (memcpy, strcpy, etc.) do not check buffer boundaries, leading to unintended writes.</p>
</li>
<li><p>Without proper bound checking, a large write can exceed the buffer size and corrupt nearby memory.</p>
</li>
</ul>
<p>Here’s a code sample to demonstrate buffer overflow in a .bss / .data section:</p>
<pre><code class="lang-c">  <span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdint.h&gt;</span></span>
  <span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>
  <span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;string.h&gt;</span></span>

  <span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> BUFFER_SIZE 300</span>

  <span class="hljs-keyword">static</span> <span class="hljs-keyword">uint16_t</span> sample_count = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">static</span> <span class="hljs-keyword">uint8_t</span> buffer[BUFFER_SIZE] = {<span class="hljs-number">0</span>};

  <span class="hljs-comment">// Function to simulate a buffer overflow scenario</span>
  <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">updateBufferWithData</span><span class="hljs-params">(<span class="hljs-keyword">uint8_t</span> *data, <span class="hljs-keyword">uint16_t</span> size)</span>
  </span>{
      <span class="hljs-comment">// Simulating a buffer overflow: No boundary check!</span>
      <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Attempting to write %d bytes at position %d...\n"</span>, size, sample_count);

      <span class="hljs-comment">// Deliberate buffer overflow for demonstration</span>
      <span class="hljs-keyword">if</span> (sample_count + size &gt; BUFFER_SIZE)
      {
          <span class="hljs-built_in">printf</span>(<span class="hljs-string">"WARNING: Buffer Overflow Occurred! Writing beyond allocated memory!\n"</span>);
      }

      <span class="hljs-comment">// Copy data (unsafe, can cause overflow)</span>
      <span class="hljs-built_in">memcpy</span>(&amp;buffer[sample_count], data, size);

      <span class="hljs-comment">// Increment sample count (incorrectly, leading to wraparound issues)</span>
      sample_count += size;
  }

  <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
  </span>{   
      <span class="hljs-comment">// Save 1 byte to buffer</span>
      <span class="hljs-keyword">uint8_t</span> data_to_buffer = <span class="hljs-number">10</span>;
      updateBufferWithData(&amp;data_to_buffer, <span class="hljs-number">1</span>);

      <span class="hljs-comment">// Save an array of 20 bytes to buffer</span>
      <span class="hljs-keyword">uint8_t</span> data_to_buffer_1[<span class="hljs-number">20</span>] = {<span class="hljs-number">5</span>};
      updateBufferWithData(data_to_buffer_1, <span class="hljs-keyword">sizeof</span>(data_to_buffer_1));

      <span class="hljs-comment">// Intentional buffer overflow: Save an array of 50 x 8 bytes (400 bytes)</span>
      <span class="hljs-keyword">uint64_t</span> data_to_buffer_2[<span class="hljs-number">50</span>] = {<span class="hljs-number">7</span>};
      updateBufferWithData((<span class="hljs-keyword">uint8_t</span>*)data_to_buffer_2, <span class="hljs-keyword">sizeof</span>(data_to_buffer_2));

      <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
  }
</code></pre>
<h3 id="heading-interrupt-driven-overflows-real-time-systems">Interrupt-Driven Overflows (Real-time Systems)</h3>
<p><strong>Issue</strong>: The interrupt service routine (ISR) may write data faster than the main task can process, leading to buffer corruption or buffer overflow if the write pointer is not properly managed.</p>
<p><strong>Example</strong>: Imagine a sensor ISR that writes incoming data into a buffer every time a new reading arrives. Meanwhile, a low-priority processing task reads and processes the data.</p>
<p>What can go wrong?</p>
<ul>
<li><p>If the ISR triggers too frequently (due to a misbehaving sensor or high interrupt priority), the buffer may fill up faster than the processing task can keep up.</p>
</li>
<li><p>This can result in one of two failures:</p>
<ol>
<li><p>Buffer Corruption: The ISR overwrites unread data, leading to loss of information.</p>
</li>
<li><p>Buffer Overflow: The ISR exceeds buffer boundaries, causing memory corruption or system crashes.</p>
</li>
</ol>
</li>
</ul>
<p>So why does this happen?</p>
<ul>
<li><p>In real-time embedded systems, ISR execution preempts lower-priority tasks.</p>
</li>
<li><p>If the processing task doesn't not get enough CPU time, the buffer may become overwritten or overflow beyond its allocated scope.</p>
</li>
</ul>
<h3 id="heading-system-state-changes-amp-buffer-corruption">System State Changes &amp; Buffer Corruption</h3>
<p><strong>Issue</strong>: The system may unexpectedly reset, enter low-power mode, or changes operating state, leaving the buffer write pointers in an inconsistent state. This can result in buffer corruption (stale or incorrect data) or buffer overflow (writing past the buffer’s limits.</p>
<p><strong>Example Scenarios</strong>:</p>
<ol>
<li><p>Low-power wake-up issue (Buffer Overflow risk): Some embedded systems enter deep sleep to conserve energy. Upon waking up, if the buffer write pointer is not correctly reinitialized, it may point outside buffer boundaries, leading to buffer overflow and unintended memory corruption.</p>
</li>
<li><p>Unexpected mode transitions: If a sensor task is writing data and the system suddenly switches modes, the buffer states and pointers may not be cleaned up. The next time the sensor task runs, it may continue writing without clearing previous data. This can cause undefined behavior due to presence of stale data.</p>
</li>
</ol>
<p>Now that you understand how buffer overflows and corruptions happen, let’s examine their consequences in embedded systems ranging from incorrect sensor readings to complete system failures, making debugging and prevention critical.</p>
<h2 id="heading-consequences-of-buffer-overflows">Consequences of Buffer Overflows</h2>
<p>Buffer overflows can be catastrophic in embedded systems, leading to system crashes, data corruption, and unpredictable behavior. Unlike general-purpose computers, many embedded devices lack memory protection, making them particularly vulnerable to buffer overflows.</p>
<p>A buffer overflow can corrupt two critical types of memory:</p>
<h3 id="heading-1-data-variables-corruption">1. Data Variables Corruption</h3>
<p>A buffer overflow can overwrite data variables, corrupting the inputs for other software modules. This can cause unexpected behavior or even system crashes if critical parameters are modified.</p>
<p>For example, a buffer overflow could accidentally overwrite a sensor calibration value stored in memory. As a result, the system would start using incorrect sensor readings, leading to faulty operation and potentially unsafe conditions.</p>
<h3 id="heading-2-function-pointer-corruption">2. Function Pointer Corruption</h3>
<p>In embedded systems, function pointers are often used for interrupt handlers, callback functions, and RTOS task scheduling. If a buffer overflow corrupts a function pointer, the system may execute unintended instructions, leading to a crash or unexpected behavior.</p>
<p>As an example, a function pointer controlling motor speed regulation could be overwritten. Instead of executing the correct function, the system would jump to a random memory address, causing a system fault or erratic motor behavior.</p>
<p>Buffer overflows are among the hardest bugs to identify and fix because their effects depend on which data is corrupted and the values it contains. A buffer overflow can affect memory in different ways:</p>
<ul>
<li><p>If a buffer overflow corrupts unused memory, the system may seem fine during testing, making the issue harder to detect.</p>
</li>
<li><p>if a buffer overflow alters critical data variables, it can cause hidden logic errors that cause unpredictable behavior.</p>
</li>
<li><p>If a buffer overflow corrupts function pointers, it may crash immediately, making the problem easier to identify.</p>
</li>
</ul>
<p>During development, if tests focus only on detecting crashes, they may overlook silent memory corruption caused by a buffer overflow. In real-world deployments, new use cases not covered in testing can trigger previously undetected buffer overflow issues, leading to unpredictable failures.</p>
<p>Buffer overflows can cause a chain reaction, where one overflow leads to another overflow or buffer corruption, resulting in widespread system failures. So how does this happen?</p>
<ol>
<li><p>A buffer overflow corrupts a critical variable (for example, a timer interval).</p>
</li>
<li><p>The corrupted variable disrupts another module (for example, triggers the timer interrupt too frequently, causing it to push more data into a buffer than intended.).</p>
</li>
<li><p>This increased interrupt frequency forces a sensor task to write data faster than intended, eventually causing another buffer overflow or corruption by overwriting unread data.</p>
</li>
</ol>
<p>This chain reaction can spread across multiple software modules, making debugging nearly impossible. In real-word applications, buffer overflows in embedded systems can be life-threatening:</p>
<ul>
<li><p>In cars: A buffer overflow in an ECU (Electronic Control Unit) could cause brake failure or unintended acceleration.</p>
</li>
<li><p>In a spacecraft: A memory corruption issue could disable navigation systems, leading to mission failure.</p>
</li>
</ul>
<p>Now that we’ve seen how buffer overflows can corrupt memory, disrupt system behavior, and even cause critical failures, the next step is understanding how to detect and fix them before they lead to serious issues.</p>
<h2 id="heading-how-to-debug-buffer-overflows">How to Debug Buffer Overflows</h2>
<p>Debugging buffer overflows in embedded systems can be complex, as their effects range from immediate crashes to silent data corruption, making them difficult to trace. A buffer overflow can cause either:</p>
<ol>
<li><p>A system crash, which is easier to detect since it halts execution or forces a system reboot.</p>
</li>
<li><p>Unexpected behavior, which is much harder to debug as it requires tracing how corrupted data affects different modules.</p>
</li>
</ol>
<p>This section focuses on embedded system debugging techniques using memory map files, debuggers (GDB/LLDB), and a structured debugging approach. Let’s look into the debuggers and memory map files.</p>
<h3 id="heading-memory-map-file-map-file">Memory Map File (.map file)</h3>
<p>A memory map file is generated during the linking process. It provides a memory layout of global/static variables, function addresses, and heap/stack locations. It provides a memory layout of Flash and RAM, including:</p>
<ul>
<li><p>Text section (.text): Stores executable code.</p>
</li>
<li><p>Read-only section (.rodata): Stores constants and string literals.</p>
</li>
<li><p>BSS section (.bss): Stores uninitialized global and static variables.</p>
</li>
<li><p>Data section (.data): Stores initialized global and static variables.</p>
</li>
<li><p>Heap and stack locations, depending on the linker script.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739064875727/1e01992d-4d9d-42fb-b971-6f4e92452c22.png" alt="Figure 1: A visual of the memory layout" class="image--center mx-auto" width="1256" height="425" loading="lazy"></p>
<p>If a buffer overflow corrupts a global variable, the .map file can identify nearby variables that may also be affected, provided the compiler has not optimized the memory allocation. Similarly, if a function pointer is corrupted, the .map file can reveal where it was stored in memory.</p>
<h3 id="heading-debuggers-gdb-amp-lldb">Debuggers (GDB &amp; LLDB)</h3>
<p>Debugging tools like GDB (GNU Debugger) and LLDB (LLVM Debugger) allow:</p>
<ul>
<li><p>Controlling execution (breakpoints, stepping through code).</p>
</li>
<li><p>Inspecting variable values and memory addresses.</p>
</li>
<li><p>Getting backtraces (viewing function calls before a crash).</p>
</li>
<li><p>Extracting core dumps from microcontrollers for post-mortem analysis.</p>
</li>
</ul>
<p>If the system halts on a crash, a backtrace (bt command in GDB) can reveal which function was executing before failure. If the overflow affects a heap-allocated variable, GDB can inspect heap memory usage to detect corruption.</p>
<h3 id="heading-the-debugging-process">The Debugging Process</h3>
<p>Now, let’s go through a step-by-step debugging process to identify and fix buffer overflows. Once a crash or unexpected behavior occurs, follow these techniques to trace the root cause:</p>
<h4 id="heading-step-1-identify-the-misbehaving-module">Step 1: Identify the misbehaving module</h4>
<p>If the system crashes, use GDB or LLDB backtrace (bt command) to locate the last executed function. If the system behaves unexpectedly, determine which software module controls the affected functionality.</p>
<h4 id="heading-step-2-analyze-inputs-and-outputs-of-the-module">Step 2: Analyze inputs and outputs of the module</h4>
<p>Every function or module has inputs and outputs. Create a truth table listing expected outputs for all possible inputs. Check if the unexpected behavior matches any undefined input combination, which may indicate corruption.</p>
<h4 id="heading-step-3-locate-memory-corruption-using-address-analysis">Step 3: Locate memory corruption using address analysis</h4>
<p>If a variable shows incorrect values, determine its physical memory location. Depending on where the variable is stored:</p>
<ol>
<li><p>Global/static variables (.bss / .data): Look up the memory map file for nearby buffers.</p>
</li>
<li><p>Heap variables: Snapshot heap allocations using GDB.  </p>
<p> Here’s an example of using GDB to find corrupted variables:</p>
<pre><code class="lang-c"> (gdb) print &amp;my_variable  # Get memory address of the variable
 $<span class="hljs-number">1</span> = (<span class="hljs-keyword">int</span> *) <span class="hljs-number">0x20001000</span>
 (gdb) x/<span class="hljs-number">10</span>x <span class="hljs-number">0x20001000</span>   # Examine memory near <span class="hljs-keyword">this</span> address, Display <span class="hljs-number">10</span> memory words in hexadecimal format starting from <span class="hljs-number">0x20001000</span>
</code></pre>
</li>
</ol>
<h4 id="heading-step-4-identify-the-overflowing-buffer">Step 4: Identify the overflowing buffer</h4>
<p>If a buffer is located just before the corrupted variable, inspect its usage in the code. Review all possible code paths that write to the buffer. Check if any design limitations could cause an overflow under a specific use cases.</p>
<h4 id="heading-step-5-fix-the-root-cause">Step 5: Fix the root cause</h4>
<p>If the buffer overflow happened due to missing bounds checks, add proper input validation to prevent it. Buffer design should enforce strict memory limits. The module should implement strict boundary checks for all inputs and maintain a consistent state.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739065828677/74322607-5997-4275-87d0-b3d0acf54373.png" alt="Figure 2: Steps to debug a buffer overflow" class="image--center mx-auto" width="1105" height="325" loading="lazy"></p>
<p>In addition to GDB/LLDB, you can also use techniques like hardware tracing and fault injection to simulate buffer overflows and observe system behavior in real-time.</p>
<p>While debugging helps identify and fix buffer overflows, prevention is always the best approach. Let’s explore techniques that can help avoid buffer overflows altogether.</p>
<h2 id="heading-how-to-prevent-buffer-overflows">How to Prevent Buffer Overflows</h2>
<p>You can often prevent buffer overflows through good software design, defensive programming, hardware protections, and rigorous testing. Embedded systems, unlike general-purpose computers, often lack memory protection mechanisms, which means that buffer overflow prevention critical for system reliability and security.</p>
<p>Here are some key techniques to help prevent buffer overflows:</p>
<h3 id="heading-defensive-programming">Defensive Programming</h3>
<p>Defensive programming helps minimize buffer overflow risks by ensuring all inputs are validated and unexpected conditions are handled safely.</p>
<p>First, it’s crucial to validate input size before writing to a buffer. Always check the write index by adding the size of data to be written prior to writing data to make sure more data is not written than the available buffer space.</p>
<p>Then you’ll want to make sure you have proper error handling and fail-safe mechanisms in place. If an input is invalid, halt execution, log the error, or switch to a safe state. Also, functions should indicate success/failure with helpful error codes to prevent misuse.</p>
<p>Sample Code:</p>
<pre><code class="lang-c">   <span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdint.h&gt;</span></span>
   <span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;string.h&gt;</span></span>
   <span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdbool.h&gt;</span></span>
   <span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

   <span class="hljs-meta">#<span class="hljs-meta-keyword">define</span> BUFFER_SIZE 300</span>

   <span class="hljs-keyword">static</span> <span class="hljs-keyword">uint16_t</span> sample_count = <span class="hljs-number">0</span>;
   <span class="hljs-keyword">static</span> <span class="hljs-keyword">uint8_t</span> buffer[BUFFER_SIZE] = {<span class="hljs-number">0</span>};

   <span class="hljs-keyword">typedef</span> <span class="hljs-keyword">enum</span>
   {
       SUCCESS = <span class="hljs-number">0</span>,
       NOT_ENOUGH_SPACE = <span class="hljs-number">1</span>,
       DATA_IS_INVALID = <span class="hljs-number">2</span>,
   } buffer_err_code_e;


   <span class="hljs-function">buffer_err_code_e <span class="hljs-title">updateBufferWithData</span><span class="hljs-params">(<span class="hljs-keyword">uint8_t</span> *data, <span class="hljs-keyword">uint16_t</span> size)</span>
   </span>{
       <span class="hljs-keyword">if</span> (data == <span class="hljs-literal">NULL</span> || size == <span class="hljs-number">0</span> || size &gt; BUFFER_SIZE)  
       {
           <span class="hljs-keyword">return</span> DATA_IS_INVALID; <span class="hljs-comment">// Invalid input size</span>
       }

       <span class="hljs-keyword">uint16_t</span> available_space = BUFFER_SIZE - sample_count;
       <span class="hljs-keyword">bool</span> can_write = (available_space &gt;= size) ? <span class="hljs-literal">true</span> : <span class="hljs-literal">false</span>;

       <span class="hljs-keyword">if</span> (!can_write)  
       {
           <span class="hljs-keyword">return</span> NOT_ENOUGH_SPACE;
       }

       <span class="hljs-comment">// Copy data safely</span>
       <span class="hljs-built_in">memcpy</span>(&amp;buffer[sample_count], data, size);
       sample_count += size;

       <span class="hljs-keyword">return</span> SUCCESS;
   }

   <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
   </span>{   
       buffer_err_code_e ret;

       <span class="hljs-comment">// Save 1 byte to buffer</span>
       <span class="hljs-keyword">uint8_t</span> data_to_buffer = <span class="hljs-number">10</span>;
       ret = updateBufferWithData(&amp;data_to_buffer, <span class="hljs-keyword">sizeof</span>(data_to_buffer));
       <span class="hljs-keyword">if</span> (ret)  
       {
           <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Buffer update didn't succeed, Err:%d\n"</span>, ret);
       }

       <span class="hljs-comment">// Save an array of 20 bytes to buffer</span>
       <span class="hljs-keyword">uint8_t</span> data_to_buffer_1[<span class="hljs-number">20</span>] = {<span class="hljs-number">5</span>};
       ret = updateBufferWithData(data_to_buffer_1, <span class="hljs-keyword">sizeof</span>(data_to_buffer_1));
       <span class="hljs-keyword">if</span> (ret)  
       {
           <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Buffer update didn't succeed, Err:%d\n"</span>, ret);
       }

       <span class="hljs-comment">// Save an array of 50 x 8 bytes, Intentional buffer overflow</span>
       <span class="hljs-keyword">uint64_t</span> data_to_buffer_2[<span class="hljs-number">50</span>] = {<span class="hljs-number">7</span>};
       ret = updateBufferWithData((<span class="hljs-keyword">uint8_t</span>*)data_to_buffer_2, <span class="hljs-keyword">sizeof</span>(data_to_buffer_2));  
       <span class="hljs-keyword">if</span> (ret)  
       {
           <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Buffer update didn't succeed, Err:%d\n"</span>, ret);
       }

       <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
   }
</code></pre>
<h3 id="heading-choosing-the-right-buffer-design-and-size">Choosing the Right Buffer Design And Size</h3>
<p>Some buffer designs handle overflow better than others. Choosing the correct buffer type and size for the application reduces the risk of corruption.</p>
<ul>
<li><p>Circular Buffers (Ring Buffers) prevent out-of-bounds writes by wrapping around. They overwrite the oldest data instead of corrupting memory. These are useful for real-time streaming data (for example, UART, sensor readings). This approach is ideal for applications where data loss is unacceptable.</p>
</li>
<li><p>Ping-Pong Buffers (Double Buffers) use two buffers. One buffer fills up with data. Then, once it’s full, it switches to the second buffer while the first one is processed. This approach is beneficial for application that have strict requirements on no data loss. The buffer design should be based on the speed of write and read tasks.</p>
</li>
</ul>
<h3 id="heading-hardware-protection">Hardware Protection</h3>
<h4 id="heading-memory-protection-unit-mpu">Memory Protection Unit (MPU)</h4>
<p>An MPU (Memory Protection Unit) helps detect unauthorized memory accesses, including buffer overflows, by restricting which regions of memory can be written to. It prevents buffer overflows from modifying critical memory regions and triggers a MemManage Fault if a process attemps to write outside an allowed region.</p>
<p>But keep in mind that, an MPU does not prevent buffer overflows – it only detects and stops execution when they occur. Not all microcontrollers have an MPU, and some low-end MCUs lack hardware protection, making software-based safeguards even more critical.</p>
<p>Modern C compilers provide several flags to identify memory errors at compile-time:</p>
<ol>
<li><p>-Wall -Wextra: Enables useful warnings</p>
</li>
<li><p>-Warray-bounds: Detects out-of-bounds array access when the array size is known at compile-time</p>
</li>
<li><p>-Wstringop-overflow: Warns about possible overflows in string functions like memcpy and strcpy.</p>
</li>
</ol>
<h3 id="heading-testing-and-validation">Testing and Validation</h3>
<p>Testing helps detect buffer overflows before deployment, reducing the risk of field failures. Unit testing each function independently with valid inputs, boundary cases, and invalid inputs helps detect buffer-related issues early. Automated testing involves feeding random and invalid inputs into the system to uncover crashes and unexpected behavior. Static Analysis Tools like Coverity, Clang Static Analyzer help detect buffer overflows before runtime. Run real-world inputs on embedded hardware to detect issues.</p>
<p>Now that we've explored how to identify, debug, and prevent buffer overflows, it’s clear that these vulnerabilities pose a significant threat to embedded systems. From silent data corruption to catastrophic system failures, the consequences can be severe.</p>
<p>But with the right debugging tools, systematic analysis, and preventive techniques, you can effectively either prevent or mitigate buffer overflows in your systems.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Buffer overflows and corruption are major challenges in embedded systems, leading to crashes, unpredictable behavior, and security risks. Debugging these issues is difficult because their symptoms vary based on system state, requiring systematic analysis using memory map files, GDB/LLDB, and structured debugging approaches.</p>
<p>In this article, we explored:</p>
<ul>
<li><p>The causes and consequences of buffer overflows and corruptions</p>
</li>
<li><p>How to debug buffer overflows using memory analysis and debugging tools</p>
</li>
<li><p>Best practices for prevention</p>
</li>
</ul>
<p>Buffer overflow prevention requires a multi-layered approach:</p>
<ol>
<li><p>Follow a structured software design process to identify risks early.</p>
</li>
<li><p>Apply defensive programming principles to validate inputs and handle errors gracefully.</p>
</li>
<li><p>Use hardware-based protections like MPUs where available.</p>
</li>
<li><p>Enable compiler flags that help identify memory errors.</p>
</li>
<li><p>Test extensively, unit testing, automated testing, and code reviews help catch vulnerabilities early.</p>
</li>
</ol>
<p>By implementing these best practices, you can minimize the risk of buffer overflows in embedded systems, improving reliability and security.</p>
<p>In embedded systems, where reliability and safety are critical, preventing buffer overflows is not just a best practice, it is a necessity. A single buffer overflow can compromise an entire system. Defensive programming, rigorous testing, and hardware protections are essential for building secure and robust embedded applications.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Add Local Storage to Your Blazor Apps with Blazored.LocalStorage ]]>
                </title>
                <description>
                    <![CDATA[ By FADAHUNSI SEYI SAMUEL One critical feature of modern web applications is their ability to store and retrieve data on the client side. This is where local storage comes into play.  In this article, we'll explore how to leverage the power of the Bla... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/use-local-storage-in-blazor-apps/</link>
                <guid isPermaLink="false">66d45edd230dff01669057fb</guid>
                
                    <category>
                        <![CDATA[ Blazor ]]>
                    </category>
                
                    <category>
                        <![CDATA[ C ]]>
                    </category>
                
                    <category>
                        <![CDATA[ localstorage ]]>
                    </category>
                
                    <category>
                        <![CDATA[ .NET ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 29 Jul 2024 13:55:34 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/07/pexels-pixabay-236698.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By FADAHUNSI SEYI SAMUEL</p>
<p>One critical feature of modern web applications is their ability to store and retrieve data on the <a target="_blank" href="https://www.cloudflare.com/learning/serverless/glossary/client-side-vs-server-side/">client side</a>. This is where <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage">local storage</a> comes into play. </p>
<p>In this article, we'll explore how to leverage the power of the <a target="_blank" href="https://www.nuget.org/packages/Blazored.LocalStorage">Blazored LocalStorage NuGet package</a> to seamlessly integrate <code>local storage</code> capabilities into your Blazor applications.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-prerequisites">Prerequisites</a></li>
<li><a class="post-section-overview" href="#heading-understanding-local-storage">Understanding Local Storage</a></li>
<li><a class="post-section-overview" href="#heading-introducing-blazoredlocalstorage">Introducing Blazored.LocalStorage</a></li>
<li><a class="post-section-overview" href="#heading-advantages-of-using-blazoredlocalstorage-in-blazor-applications">Advantages of Using Blazored.LocalStorage in Blazor Applications</a></li>
<li><a class="post-section-overview" href="#heading-how-to-install-blazoredlocalstorage">How to Install Blazored.LocalStorage</a></li>
<li><a class="post-section-overview" href="#heading-install-using-the-nuget-package-manager">Install Using Nuget Package Manager</a></li>
<li><a class="post-section-overview" href="#heading-install-using-the-net-cli">Install Using the .NET CLI</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-blazoredlocalstorage">How to Use Blazored.LocalStorage</a></li>
<li><a class="post-section-overview" href="#heading-advanced-features-and-techniques">Advanced Features and Techniques</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<h3 id="heading-prerequisites">Prerequisites</h3>
<p>Make sure you have the necessary tools installed on your computer before continuing with this guide:</p>
<ul>
<li>To build and update <a target="_blank" href="https://learn.microsoft.com/en-us/aspnet/core/blazor/?view=aspnetcore-8.0">Blazor</a> projects, you'll need <a target="_blank" href="https://visualstudio.microsoft.com/downloads/">Visual Studio</a>, a feature-rich Integrated Development Environment (IDE) which you can download from the official <a target="_blank" href="https://visualstudio.microsoft.com/downloads/">Microsoft website here</a>.</li>
<li>The <a target="_blank" href="https://dotnet.microsoft.com/en-us/download">.NET SDK</a> (Software Development Kit) has everything you need to create and execute <a target="_blank" href="https://dotnet.microsoft.com/en-us/learn/dotnet/what-is-dotnet">.NET</a> apps, and it's required for Blazor projects. Make sure your computer has the <code>.NET SDK</code> installed.</li>
<li>Basic knowledge of <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/csharp/">C#</a> and Blazor.</li>
</ul>
<p>With these installed, will be ready to follow along.</p>
<h2 id="heading-understanding-local-storage">Understanding Local Storage</h2>
<p>Local storage is a <code>key-value</code> pair storage mechanism supported by modern web browsers. It provides a simple way to store data persistently on the user's device. Unlike <code>session storage</code>, which is cleared when the browser session ends, <code>local storage</code> remains intact even after closing the browser window.</p>
<p><a target="_blank" href="https://www.nuget.org/packages/Blazored.LocalStorage">Blazored.LocalStorage</a> is a powerful library that simplifies working with the browser's local storage <code>API</code> (Application Programming Interface) within Blazor applications. It provides a convenient <code>API</code> for storing, retrieving, and managing data in local storage.</p>
<p>By abstracting away the complexities of directly interacting with the <code>localStorage</code> API, this package provides an intuitive and type-safe interface. It lets you focus on building feature-rich Blazor applications without worrying about the underlying storage mechanisms.</p>
<h2 id="heading-introducing-blazoredlocalstorage">Introducing Blazored.LocalStorage</h2>
<p><code>Blazored.LocalStorage</code> is an open-source library designed to provide easy and accessible local storage management in Blazor applications. This library is compatible with both <a target="_blank" href="https://www.pragimtech.com/blog/blazor-webAssembly/what-is-blazor-webassembly/">Blazor WebAssembly</a> and <a target="_blank" href="https://www.c-sharpcorner.com/article/understanding-server-side-blazor/">Blazor Server</a> projects. This makes it a versatile choice for Blazor developers looking to enhance their applications with persistent, client-side storage capabilities.</p>
<p>At its core, <code>Blazored.LocalStorage</code> facilitates the storage and retrieval of data in the browser's local storage, allowing data to persist across browser sessions. </p>
<p>This is particularly useful for storing user preferences, application state, and other data that needs to persist between page reloads without the need for a database or backend storage solution.</p>
<h3 id="heading-advantages-of-using-blazoredlocalstorage-in-blazor-applications">Advantages of Using Blazored.LocalStorage in Blazor Applications</h3>
<p>The inclusion of <code>Blazored.LocalStorage</code> in Blazor applications comes with a host of benefits, including:</p>
<ul>
<li>Simplified State Management: By leveraging local storage, applications can maintain state more effectively across user sessions, enhancing the user experience.</li>
<li>Performance Improvements: Storing data locally reduces the need for frequent server requests, leading to faster application performance and reduced server load.</li>
<li>Enhanced User Experience: Preferences and application states can be preserved, meaning users do not need to reconfigure settings or lose their place in the application upon returning.</li>
<li>Easy Integration: The <code>API</code> provided by <code>Blazored.LocalStorage</code> is designed to be intuitive and straightforward, ensuring that developers can integrate local storage capabilities into their applications with minimal effort.</li>
<li>Cross-Session Persistence: Unlike session storage or in-memory data storage, local storage ensures that data persists across browser sessions and tab closures, providing a more consistent user experience.</li>
</ul>
<h2 id="heading-how-to-install-blazoredlocalstorage">How to Install Blazored.LocalStorage</h2>
<p>Integrating <code>Blazored.LocalStorage</code> into your Blazor project is straightforward, with support for installation via the <code>NuGet Package Manager</code> or the <code>.NET CLI</code> (Command Line Interpreter).</p>
<h3 id="heading-install-using-the-nuget-package-manager">Install Using the NuGet Package Manager</h3>
<p>Using <code>Visual Studio</code>, you can easily add <code>Blazored.LocalStorage</code> by following these steps:</p>
<ul>
<li>Open your Blazor project in Visual Studio.</li>
<li>Navigate to the “Solution Explorer”, right-click on "Dependencies", and select “Manage NuGet Packages”.</li>
</ul>
<p><img src="https://hackmd.io/_uploads/S1ckU8ll0.png" alt="Annotation 2024-04-07 181852" width="600" height="400" loading="lazy"></p>
<ul>
<li>In the NuGet Package Manager, click on the “Browse” tab and search for “Blazored.LocalStorage”.</li>
</ul>
<p><img src="https://hackmd.io/_uploads/HkBjUUxxC.png" alt="2024-04-07_18-22-49" width="600" height="400" loading="lazy"></p>
<ul>
<li>Find the package in the list, select it, and click “Install”.</li>
</ul>
<p>Visual Studio will handle the rest, adding the package to your project along with any dependencies.</p>
<h3 id="heading-install-using-the-net-cli">Install Using the .NET CLI</h3>
<p>For those who prefer using the command line or are working within a development environment other than Visual Studio, the <code>.NET CLI</code> provides a simple method to add <code>Blazored.LocalStorage</code>:</p>
<pre><code class="lang-csharp">dotnet <span class="hljs-keyword">add</span> package Blazored.LocalStorage
</code></pre>
<p>Run the command above in your <code>terminal</code> or <code>command prompt</code> from the root directory of your Blazor project. The CLI will download and install <code>Blazored.LocalStorage</code> along with any necessary dependencies.</p>
<h2 id="heading-how-to-use-blazoredlocalstorage">How to Use Blazored.LocalStorage</h2>
<p>Let's dive into some basic examples of using Blazored.LocalStorage in a Blazor application.</p>
<h3 id="heading-how-to-register-blazoredlocalstorage-in-your-blazor-application">How to Register Blazored.LocalStorage in your Blazor Application</h3>
<p>We will register<code>Blazored.LocalStorage</code> into the root of the application, so that it will be available to use everywhere in the application.</p>
<p>In the <code>program.cs</code> file, which is our root file, we will register the <code>Blazored.LocalStorage</code> service by doing the following:</p>
<pre><code class="lang-csharp">builder.Services.AddBlazoredLocalStorage();
</code></pre>
<p>The code snippet above registers the <code>Blazored.LocalStorage</code> into the application. For this to work, make sure you add the code below to the top of the <code>program.cs</code> file:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> Blazored.LocalStorage;
</code></pre>
<p>The code snippet above makes sure that the <code>Blazored.LocalStorage</code> is being imported to be used in the file. If you've added everything correctly, your <code>program.cs</code> file should look like this:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> BlazorApp9.Components;
<span class="hljs-keyword">using</span> Blazored.LocalStorage;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">BlazorApp9</span>;

<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Program</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <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>
    {
        <span class="hljs-keyword">var</span> builder = WebApplication.CreateBuilder(args);

        builder.Services.AddRazorComponents()
            .AddInteractiveServerComponents();

        builder.Services.AddBlazoredLocalStorage();

        <span class="hljs-keyword">var</span> app = builder.Build();

        <span class="hljs-keyword">if</span> (!app.Environment.IsDevelopment())
        {
            app.UseExceptionHandler(<span class="hljs-string">"/Error"</span>);
            app.UseHsts();
        }

        app.UseHttpsRedirection();

        app.UseStaticFiles();
        app.UseAntiforgery();

        app.MapRazorComponents&lt;App&gt;()
            .AddInteractiveServerRenderMode();

        app.Run();
    }
}
</code></pre>
<p>The above is the full code that should be in your <code>program.cs</code> file. With this, you can now use <code>Blazored.LocalStorage</code> anywhere in the application to store and receive data.</p>
<h3 id="heading-how-to-store-and-retrieve-data-in-blazoredlocalstorage">How to Store and Retrieve Data in Blazored.LocalStorage</h3>
<p>Let's consider a simple scenario where we want to store and retrieve a piece of data using local storage. We'll create a Blazor page with two buttons: one to store data and another to retrieve it.</p>
<pre><code class="lang-csharp">@page <span class="hljs-string">"/"</span>

@inject Blazored.LocalStorage.ILocalStorageService localStorage
@rendermode RenderMode.InteractiveServer

&lt;h3&gt;Local Storage Example&lt;/h3&gt;

&lt;input @bind-<span class="hljs-keyword">value</span>=<span class="hljs-string">"@inputData"</span> /&gt;

&lt;button @onclick=<span class="hljs-string">"StoreData"</span>&gt;Store Data&lt;/button&gt;
&lt;button @onclick=<span class="hljs-string">"RetrieveData"</span>&gt;Retrieve Data&lt;/button&gt;

&lt;p&gt;The retrieved data <span class="hljs-keyword">from</span> the LocalStorage: @storedData &lt;/p&gt;

@code {
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">const</span> <span class="hljs-keyword">string</span> dataKey = <span class="hljs-string">"localStorageKey"</span>;

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">string</span>? storedData;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">string</span>? inputData;

    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">StoreData</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-keyword">if</span>(!<span class="hljs-keyword">string</span>.IsNullOrWhiteSpace(inputData))
        {
            <span class="hljs-keyword">await</span> localStorage.SetItemAsync(dataKey, inputData);
            inputData = <span class="hljs-string">""</span>;
        }
    }

    <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">OnAfterRenderAsync</span>(<span class="hljs-params"><span class="hljs-keyword">bool</span> firstRender</span>)</span>
    {
        <span class="hljs-keyword">if</span> (firstRender)
        {
            <span class="hljs-keyword">await</span> RetrieveData();
        }
    }

    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">RetrieveData</span>(<span class="hljs-params"></span>)</span>
    {
        storedData = <span class="hljs-keyword">await</span> localStorage.GetItemAsync&lt;<span class="hljs-keyword">string</span>&gt;(dataKey);
    }
}
</code></pre>
<p>In the code snippet above, the <code>@inject Blazored.LocalStorage.ILocalStorageService localStorage</code> injects the local storage service to interact with the browser's local storage. The <code>@rendermode RenderMode.InteractiveServer</code> specifies that the page should be rendered as an interactive server-side component. Without the interactive server, the page will not be interactive.</p>
<p>The input field binds to <code>inputData</code> using the <code>@bind-value</code> attribute, allowing users to enter data they wish to store. The <code>dataKey</code> is a constant variable used to store and retrieve data from local storage. The <code>storedData</code> and <code>inputData</code> variables are used to hold the data to be stored and retrieved.</p>
<p>The <code>StoreData</code> method checks to see if <code>inputData</code> is not empty. If not, it stores it in local storage using <code>dataKey</code>, and clears the input field. </p>
<p><code>OnAfterRenderAsync</code> is triggered after the component's first render. It retrieves data from local storage to ensure that data persists even after the page is reloaded. </p>
<p><code>RetrieveData</code> retrieves data from local storage and assigns it to <code>storedData</code> for display.</p>
<p><img src="https://hackmd.io/_uploads/H1DGRAL-0.gif" alt="2024-04-15_00-52-31 (1) (1) (1) (1)" width="600" height="400" loading="lazy"></p>
<p>The video above explains how to store and retrieve data stored in localstorage on the client-side.</p>
<h2 id="heading-advanced-features-and-techniques">Advanced Features and Techniques</h2>
<p>In this section, we'll talk about how you can set an expiration date on your data, and how the stored data can be encrypted and decrypted for security.</p>
<h3 id="heading-how-to-manage-the-expiration-of-stored-data">How to Manage the Expiration of Stored Data</h3>
<p>To manage the expiration of your stored data, you will create a helper class that stores data along with an expiration timestamp. Create a file called <code>StorageItem.cs</code> which will contain the code below:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">StorageItem</span>&lt;<span class="hljs-title">T</span>&gt;
{
    <span class="hljs-keyword">public</span> required T Data { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> DateTime Expiry { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
}
</code></pre>
<p>The code snippet above is a <code>StorageItem&lt;T&gt;</code> class, which is a generic class that can hold data of any type <code>T</code> and an expiry date <code>DateTime</code>. The Data property is required to be set when an instance of <code>StorageItem</code> is created or initialized, ensuring that it always has a valid value. The <code>Expiry</code> property represents the expiration date of the stored data.</p>
<p>Next, you'll create a file which will be a class that contains methods to set and get from the LocalStorage, with an expiration time. Create a file called <code>LocalStorageHelper.cs</code>:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> Blazored.LocalStorage;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">BlazorApp9.Components.Helpers</span>;

<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">class</span> <span class="hljs-title">LocalStorageHelper</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">SetItemAsyncWithExpiry</span>&lt;<span class="hljs-title">T</span>&gt;(<span class="hljs-params">ILocalStorageService localStorageService, <span class="hljs-keyword">string</span> key, TimeSpan expiry, T data</span>)</span>
    {
        StorageItem&lt;T&gt; storageItem = <span class="hljs-keyword">new</span> StorageItem&lt;T&gt;
        {
            Data = data,
            Expiry = DateTime.UtcNow.Add(expiry)
        };

        <span class="hljs-keyword">await</span> localStorageService.SetItemAsync(key, storageItem);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">async</span> <span class="hljs-title">Task</span>&lt;<span class="hljs-title">T</span>?&gt; <span class="hljs-title">GetItemAsyncWithExpiry</span>&lt;<span class="hljs-title">T</span>&gt;(<span class="hljs-params">ILocalStorageService localStorageService, <span class="hljs-keyword">string</span> key</span>)</span>
    {
         <span class="hljs-keyword">var</span> storageItem = <span class="hljs-keyword">await</span> localStorageService.GetItemAsync&lt;StorageItem&lt;T&gt;&gt;(key);

        <span class="hljs-keyword">if</span>(storageItem <span class="hljs-keyword">is</span> <span class="hljs-literal">null</span>) {
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">default</span>;
        }

        <span class="hljs-keyword">if</span> (storageItem.Expiry &lt; DateTime.UtcNow)
        {
            <span class="hljs-keyword">await</span> localStorageService.RemoveItemAsync(key);
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">default</span>;
        }
        <span class="hljs-keyword">return</span> storageItem.Data;
    }
}
</code></pre>
<p>In the code above, you can see the necessary <code>using</code> directive for the <code>Blazored.LocalStorage</code> library. It provides easy access to the browser's local storage from Blazor applications. </p>
<p>This is followed by the declaration of the namespace <code>BlazorApp9.Components.Helpers</code>. This organizes the code and indicates that this helper is part of a specific component's helpers within the Blazor application.</p>
<p>Next, the <code>LocalStorageHelper</code> class is defined as a <code>static</code> class. A static class is one that cannot be instantiated and can only contain static members (using non static methods or properties will not be accepted). </p>
<p>Within the <code>LocalStorageHelper</code> class, two <code>static</code> asynchronous methods are defined: <code>SetItemAsyncWithExpiry</code> and <code>GetItemAsyncWithExpiry</code>.</p>
<p>The <code>SetItemAsyncWithExpiry</code> method is responsible for storing an item in the local storage with an associated expiry time. It accepts an <code>ILocalStorageService</code> instance for interacting with local storage, a <code>key</code> <code>string</code> to identify the stored item, a <code>TimeSpan</code> value representing the expiry duration, and the actual data to be stored. </p>
<p>Inside the method, a <code>StorageItem&lt;T&gt;</code> object is created, where <code>T</code> is the type of data being stored. This object includes the data and the expiry time, which is calculated by adding the specified <code>TimeSpan</code> to the current <a target="_blank" href="https://www.space.com/what-is-utc.html">UTC time</a>. </p>
<p>This <code>StorageItem</code> object is then serialized and saved in local storage under the given key using the <code>SetItemAsync</code> method of <code>ILocalStorageService</code>.</p>
<p>The <code>GetItemAsyncWithExpiry</code> method is responsible for retrieving an item from local storage and checking if it has expired. It also accepts an <code>ILocalStorageService</code> instance and a <code>key</code> <code>string</code>. </p>
<p>This method attempts to retrieve the stored <code>StorageItem&lt;T&gt;</code> object using the <code>key</code>. If the retrieved item is <code>null</code>, it returns the default value for the type <code>T</code> (typically <code>null</code> for reference types and zero or equivalent for value types). </p>
<p>If the item is found but its expiry time is earlier than the current UTC time, it means the item has expired. In this case, the item is removed from the local storage using the <code>RemoveItemAsync</code> method of <code>ILocalStorageService</code>, and the method returns the default value for <code>T</code>. If the item is valid and has not expired, the method returns the stored data.</p>
<h3 id="heading-how-to-implement-encryption-and-decryption">How to Implement Encryption and Decryption</h3>
<p>In this section, we will explore a utility file that provides encryption and decryption functionalities for a Blazor application. </p>
<p>The <code>EncryptionHelper.cs</code> class includes methods for encrypting and decrypting strings, as well as methods for serializing objects to <a target="_blank" href="https://www.w3schools.com/whatis/whatis_json.asp">JSON (Javascript Object Notation)</a> and then encrypting them. This ensures that sensitive data can be securely stored and transmitted. </p>
<p>Let’s dive into the code to understand how these methods work and how you can use them. Add the following code for this file:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> System.Security.Cryptography;
<span class="hljs-keyword">using</span> System.Text;
<span class="hljs-keyword">using</span> System.Text.Json;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">BlazorApp9.Components.Helpers</span>;

<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">class</span> <span class="hljs-title">EncryptionHelper</span>
{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">readonly</span> <span class="hljs-keyword">string</span> EncryptionKey = <span class="hljs-string">"your-encryption-key"</span>;

    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">byte</span>[] <span class="hljs-title">GetKeyBytes</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> key</span>)</span>
    {

        <span class="hljs-keyword">byte</span>[] keyBytes = Encoding.UTF8.GetBytes(key);
        Array.Resize(<span class="hljs-keyword">ref</span> keyBytes, <span class="hljs-number">32</span>);
        <span class="hljs-keyword">return</span> keyBytes;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">string</span> <span class="hljs-title">Encrypt</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> plainText</span>)</span>
    {
        <span class="hljs-keyword">byte</span>[] iv = <span class="hljs-keyword">new</span> <span class="hljs-keyword">byte</span>[<span class="hljs-number">16</span>];
        <span class="hljs-keyword">byte</span>[] array;

        <span class="hljs-keyword">using</span> (Aes aes = Aes.Create())
        {
            aes.Key = GetKeyBytes(EncryptionKey);
            aes.IV = iv;

            ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);

            <span class="hljs-keyword">using</span> (MemoryStream memoryStream = <span class="hljs-keyword">new</span> MemoryStream())
            {
                <span class="hljs-keyword">using</span> (CryptoStream cryptoStream = <span class="hljs-keyword">new</span> CryptoStream((Stream)memoryStream, encryptor, CryptoStreamMode.Write))
                {
                    <span class="hljs-keyword">using</span> (StreamWriter streamWriter = <span class="hljs-keyword">new</span> StreamWriter((Stream)cryptoStream))
                    {
                        streamWriter.Write(plainText);
                    }

                    array = memoryStream.ToArray();
                }
            }
        }

        <span class="hljs-keyword">return</span> Convert.ToBase64String(array);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">string</span> <span class="hljs-title">Decrypt</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> cipherText</span>)</span>
    {
        <span class="hljs-keyword">byte</span>[] iv = <span class="hljs-keyword">new</span> <span class="hljs-keyword">byte</span>[<span class="hljs-number">16</span>];
        <span class="hljs-keyword">byte</span>[] buffer = Convert.FromBase64String(cipherText);

        <span class="hljs-keyword">using</span> (Aes aes = Aes.Create())
        {
            aes.Key = GetKeyBytes(EncryptionKey);
            aes.IV = iv;

            ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);

            <span class="hljs-keyword">using</span> (MemoryStream memoryStream = <span class="hljs-keyword">new</span> MemoryStream(buffer))
            {
                <span class="hljs-keyword">using</span> (CryptoStream cryptoStream = <span class="hljs-keyword">new</span> CryptoStream((Stream)memoryStream, decryptor, CryptoStreamMode.Read))
                {
                    <span class="hljs-keyword">using</span> (StreamReader streamReader = <span class="hljs-keyword">new</span> StreamReader((Stream)cryptoStream))
                    {
                        <span class="hljs-keyword">return</span> streamReader.ReadToEnd();
                    }
                }
            }
        }
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">string</span> <span class="hljs-title">SerializeAndEncrypt</span>&lt;<span class="hljs-title">T</span>&gt;(<span class="hljs-params">T data</span>)</span>
    {
        <span class="hljs-keyword">var</span> jsonString = JsonSerializer.Serialize(data);
        <span class="hljs-keyword">return</span> Encrypt(jsonString);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> T <span class="hljs-title">DecryptAndDeserialize</span>&lt;<span class="hljs-title">T</span>&gt;(<span class="hljs-params"><span class="hljs-keyword">string</span> cipherText</span>)</span>
    {
        <span class="hljs-keyword">var</span> json = Decrypt(cipherText);
        <span class="hljs-keyword">return</span> JsonSerializer.Deserialize&lt;T&gt;(json);
    }
}
</code></pre>
<p>The <code>EncryptionHelper</code> class is a static helper class designed for encrypting and decrypting data. This is particularly useful for securing sensitive information in a Blazor application. </p>
<p>The class above defines a <code>static</code> <code>readonly</code> field <code>EncryptionKey</code> which holds the encryption key. This key is crucial for both the encryption and decryption processes. It's important to use a strong and securely stored key.</p>
<p>The <code>GetKeyBytes</code> method converts the string key into a byte array and ensures its length is 32 bytes. This is because <a target="_blank" href="https://www.techtarget.com/searchsecurity/definition/Advanced-Encryption-Standard">the AES encryption</a> algorithm requires a 256-bit key, which is 32 bytes long.</p>
<p>The <code>Encrypt</code> method encrypts a <code>plaintext</code> string using <code>AES</code> encryption. It first creates an initialization vector (IV) of 16 bytes, which is required by the <code>AES</code> algorithm. The method then sets up an <code>AES</code> object with the encryption key and IV, and uses a <code>CryptoStream</code> to write the encrypted data to a memory stream. This encrypted data is then converted to a <code>base64</code> string for easy storage and transmission.</p>
<p>The <code>Decrypt</code> method performs the reverse operation. It converts a <code>base64</code> string back to a byte array, sets up the <code>AES</code> object with the same key and IV, and uses a <code>CryptoStream</code> to read the decrypted data from the memory stream. The result is the original plaintext string.</p>
<p>The <code>EncryptionHelper</code> class provides two methods for handling complex data structures: <code>SerializeAndEncrypt</code> and <code>DecryptAndDeserialize</code>. The <code>SerializeAndEncrypt</code> method first serializes an object to a <code>JSON</code> string using <code>JsonSerializer.Serialize</code>, and then encrypts this <code>JSON</code> string using the <code>Encrypt</code> method. This allows complex objects to be securely stored in an encrypted format.</p>
<p>The <code>DecryptAndDeserialize</code> method decrypts an encrypted <code>JSON</code> string back into its original form and then deserializes it into an object of type T using <code>JsonSerializer.Deserialize</code>. This combination of decryption and deserialization ensures that complex data can be securely retrieved and used within the application.</p>
<h3 id="heading-how-to-connect-the-expiration-and-encryption-to-the-user-interface">How to Connect the Expiration and Encryption to the User Interface</h3>
<p>Now we'll walk through a Blazor component (<code>Home.razor</code>) that allows users to store and retrieve encrypted data in the browser's local storage. This ensures that sensitive information is protected and automatically expires when no longer needed. </p>
<p>This approach combines the ease of local storage with the security of encryption, providing a robust solution for managing user data in web applications. Let's dive into the code to see how it works.</p>
<pre><code class="lang-csharp"> @page <span class="hljs-string">"/"</span>
@using BlazorApp9.Components.Helpers

@inject Blazored.LocalStorage.ILocalStorageService localStorage
@rendermode RenderMode.InteractiveServer

&lt;h3&gt;Local Storage Example&lt;/h3&gt;

&lt;input @bind-<span class="hljs-keyword">value</span>=<span class="hljs-string">"@inputData"</span> /&gt;

&lt;button @onclick=<span class="hljs-string">"StoreData"</span>&gt;Store Data&lt;/button&gt;
&lt;button @onclick=<span class="hljs-string">"RetrieveData"</span>&gt;Retrieve Data&lt;/button&gt;

&lt;p&gt;The retrieved data <span class="hljs-keyword">from</span> the LocalStorage: @storedData &lt;/p&gt;

@code {
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">const</span> <span class="hljs-keyword">string</span> dataKey = <span class="hljs-string">"localStorageKey"</span>;

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">string</span>? storedData;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">string</span>? inputData;

    <span class="hljs-keyword">bool</span> isDataLoaded = <span class="hljs-literal">false</span>;

    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">StoreData</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-keyword">if</span> (!<span class="hljs-keyword">string</span>.IsNullOrWhiteSpace(inputData))
        {
            <span class="hljs-keyword">string</span> encryptData = EncryptionHelper.SerializeAndEncrypt(inputData);
            <span class="hljs-keyword">await</span> LocalStorageHelper.SetItemAsyncWithExpiry(localStorage, dataKey, TimeSpan.FromMinutes(<span class="hljs-number">30</span>), encryptData);
            inputData = <span class="hljs-string">""</span>;
        }
    }

    <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">OnAfterRenderAsync</span>(<span class="hljs-params"><span class="hljs-keyword">bool</span> firstRender</span>)</span>
    {
        <span class="hljs-keyword">if</span> (firstRender &amp;&amp; !isDataLoaded)
        {
            <span class="hljs-keyword">await</span> RetrieveData();
            isDataLoaded = <span class="hljs-literal">true</span>;
            StateHasChanged();
        }
    }

    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">RetrieveData</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-keyword">string</span> encryptData = <span class="hljs-keyword">await</span> LocalStorageHelper.GetItemAsyncWithExpiry&lt;<span class="hljs-keyword">string</span>&gt;(localStorage, dataKey);
        storedData = encryptData != <span class="hljs-literal">null</span> ? EncryptionHelper.DecryptAndDeserialize&lt;<span class="hljs-keyword">string</span>&gt;(encryptData) : <span class="hljs-string">"Data not found or expired."</span>;
    }
}
</code></pre>
<p>In the code above, the <code>StoreData</code> method checks if <code>inputData</code> is valid, encrypts it using <code>EncryptionHelper.SerializeAndEncrypt</code>, and stores it in local storage with a thirty-minute expiry using <code>LocalStorageHelper.SetItemAsyncWithExpiry</code>. The input field is then cleared.</p>
<p>The <code>OnAfterRenderAsync</code> method retrieves data from local storage after the component's initial render. This ensures previously stored data is loaded when the page first displays. It runs once, setting <code>isDataLoaded</code> to true and calling <code>StateHasChanged</code> to update the user interface (UI).</p>
<p>The <code>RetrieveData</code> method fetches data from local storage using <code>LocalStorageHelper.GetItemAsyncWithExpiry</code>. If the data is found and valid, it decrypts and deserializes it using <code>EncryptionHelper.DecryptAndDeserialize</code>. If not, it sets <code>storedData</code> to "<code>Data not found or expired.</code>"</p>
<p><img src="https://hackmd.io/_uploads/BJRDqJUNR.gif" alt="2024-05-30_11-18-37 (1) (2) (1)" width="600" height="400" loading="lazy"></p>
<p>The video above demonstrates how you can implement the concepts discussed in this guide in a web application.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p><code>Blazored.LocalStorage</code> offers a powerful and easy-to-use solution for managing user information in Blazor applications. Its integration brings numerous benefits, including enhanced state management, improved performance, and a better user experience.</p>
<p>After reading through this article and trying out the code for yourself, you should be able to incorporate local storage capabilities into any Blazor project. This will help you unlock the full potential of client-side storage in your web applications.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How To Use LINQ in C# – With Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ .Net (pronounced as "dot net") has many internal libraries and tools, but one that wields great power is LINQ (Language Integrated Query). It can be used in two ways: the language-level query syntax, or the LINQ API. In this article, we'll explore: ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-linq/</link>
                <guid isPermaLink="false">66bb8896deef71ff683a6d1e</guid>
                
                    <category>
                        <![CDATA[ C ]]>
                    </category>
                
                    <category>
                        <![CDATA[ .NET ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Grant Riordan ]]>
                </dc:creator>
                <pubDate>Mon, 15 Jul 2024 20:59:47 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/07/How-to-use-linq.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>.Net (pronounced as "dot net") has many internal libraries and tools, but one that wields great power is LINQ (Language Integrated Query). It can be used in two ways: the language-level query syntax, or the LINQ API.</p>
<p>In this article, we'll explore:</p>
<ul>
<li>What LINQ is.</li>
<li>How to use it.</li>
<li>Examples of some common LINQ methods.</li>
</ul>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-language-level-query-syntax">Language Level Query Syntax</a></li>
<li><a class="post-section-overview" href="#heading-method-syntax">Method Syntax</a></li>
<li><a class="post-section-overview" href="#heading-common-linq-api-methods">Common LINQ API Methods</a><ul>
<li><a class="post-section-overview" href="#heading-orderby-method">OrderBy Method</a></li>
<li><a class="post-section-overview" href="#heading-first-method">First Method</a></li>
<li><a class="post-section-overview" href="#heading-single-and-singleordefault-method">Single/SingleOrDefault Method</a></li>
<li><a class="post-section-overview" href="#heading-select-method">Select Method</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-how-to-combine-methods">How to Combine Methods</a></li>
<li><a class="post-section-overview" href="#heading-deferred-execution">Deferred Execution</a></li>
<li><a class="post-section-overview" href="#heading-how-to-chain-iqueryable-api-methods">How to Chain IQueryable API Methods</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<p>We'll be utilizing an <code>Animal</code> class in this article:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Animal</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-keyword">public</span> <span class="hljs-keyword">int</span> Age {<span class="hljs-keyword">get</span>;<span class="hljs-keyword">set</span>;}
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Sound { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
}
</code></pre>
<h2 id="heading-language-level-query-syntax">Language Level Query Syntax</h2>
<p>You may see something that resembles a SQL query in some code snippets. For example:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> animals = <span class="hljs-keyword">new</span> List&lt;Animal&gt;
{
    <span class="hljs-keyword">new</span> Animal { Name = <span class="hljs-string">"Dog"</span>, Age = <span class="hljs-number">2</span>, Sound = <span class="hljs-string">"Bark"</span> },
    <span class="hljs-keyword">new</span> Animal { Name = <span class="hljs-string">"Cat"</span>, Age = <span class="hljs-number">2</span>, Sound = <span class="hljs-string">"Meow"</span> },
    <span class="hljs-keyword">new</span> Animal { Name = <span class="hljs-string">"Fox"</span>, Age = <span class="hljs-number">5</span>, Sound = <span class="hljs-string">"Bark"</span> }
};


<span class="hljs-keyword">var</span> barkingAnimals =
    <span class="hljs-keyword">from</span> animal <span class="hljs-keyword">in</span> animals
    <span class="hljs-keyword">where</span> animal.Sound == <span class="hljs-string">"Bark"</span>
    <span class="hljs-keyword">select</span> animal;
</code></pre>
<p>You can build queries similar to SQL for complex tasks, but this can be excessive. You can simplify these queries using the LINQ API methods syntax.</p>
<h2 id="heading-method-syntax">Method Syntax</h2>
<p>The LINQ API methods utilizes a predicate (in the form of a lambda extension) to determine the criteria.</p>
<p>We can write the above query using the method syntax like so:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> barkingAnimals = animals.Where(x=&gt; x.Sound == <span class="hljs-string">"Bark"</span>).ToList();
</code></pre>
<p>It's a lot easier to write and much more concise for such a simple query.</p>
<p>It reads a lot better too: barking Animals equals all the animals where the sound property equals <code>Bark</code>.</p>
<p>LINQ querying methods all return an <code>IQueryable</code> object. This informs the compiler that the variable is not the result of the query, but the definition of the query. [see deferred execution later in this article.]</p>
<p>In order to use the results of the query we can either:</p>
<ul>
<li>Iterate over the "queryable" object (for example: using a ForEach loop)</li>
<li>Convert to an IEnunerable type. For example: a List/Array.</li>
</ul>
<h2 id="heading-common-linq-api-methods">Common LINQ API Methods</h2>
<h3 id="heading-ia"> </h3>
<p>OrderBy Method</p>
<p><code>OrderBy</code> is a useful LINQ API method that lets you order any IEnumerable object.</p>
<p>We can use it like so:</p>
<pre><code class="lang-csharp">
<span class="hljs-keyword">var</span> orderedByAge = people.OrderBy(x=&gt;x.Age);

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

<span class="hljs-keyword">var</span> orderedByAgeDescending = people.OrderByDescending(x=&gt;x.Age);
</code></pre>
<p>The above shows examples of ordering by Age in both ascending and descending order.</p>
<h3 id="heading-first-method">First Method</h3>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> first = animals.First(x=&gt; x.Sound == <span class="hljs-string">"Bark"</span>);
</code></pre>
<p>This will return the first object from the list that matches the criteria.</p>
<h3 id="heading-single-and-singleordefault-method">Single and SingleOrDefault Method</h3>
<p>This is used when you know/expect that there will be only one object that matches your criteria.</p>
<p>Example:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> cat = animals.Single(x=&gt;x.Name == <span class="hljs-string">"Cat"</span>);
</code></pre>
<p>Data can change over time, leading to unexpected results. Writing defensive code is important. If multiple objects named "Cat" are found, an uncaught error will occur. To prevent this, use the <code>SingleOrDefault</code> method, which returns a default value (null for strings) on error. Then check if the cat variable is not null.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> cat = animals.SingleOrDefault(x=&gt; x.Name==<span class="hljs-string">"Cat"</span>);

<span class="hljs-keyword">if</span>(cat != <span class="hljs-literal">null</span>){
  Console.WriteLine(<span class="hljs-string">"A single cat was found"</span>);
}
</code></pre>
<h3 id="heading-select-method">Select Method</h3>
<p>Let's say that you wish to return only the types of animal, from the <code>Animal</code> object. This can be accomplished with the <code>Select</code> method. This will create a new object for each element in the list/array.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> typesOfAnimal = animals.Select(x=&gt;x.Name).ToList();
</code></pre>
<p>But what if you want to return their name and sound? That's just as easy with the <code>Select</code> method. However, you'll have to create an anonymous object instead of just returning the property.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> animals = animals.Select(x=&gt; { Name = x.Name, 
Noise = x.Sound}).ToList();
</code></pre>
<p>This should now return a list of anonymous objects, with a <code>Name</code> and a <code>Sound</code> property.</p>
<h2 id="heading-how-to-combine-methods">How to Combine Methods</h2>
<p>Using the <code>People</code> class:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Person</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-keyword">public</span> <span class="hljs-keyword">string</span> Address { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
}
</code></pre>
<pre><code><span class="hljs-keyword">var</span> people = <span class="hljs-keyword">new</span> List&lt;Person&gt;()
{
    <span class="hljs-keyword">new</span>() { Name = <span class="hljs-string">"Harry Potter"</span>, Address = <span class="hljs-string">"123 Privet Drive, Hogwarts, United Kingdom"</span> },
    <span class="hljs-keyword">new</span>() { Name = <span class="hljs-string">"Alex the Kidd"</span>, Address = <span class="hljs-string">"Rock Paper Scissors Avenue, United Kingdom"</span> },
    <span class="hljs-keyword">new</span>() { Name = <span class="hljs-string">"Donkey Kong"</span>, Address = <span class="hljs-string">" The Monkey Temple, Jungle"</span> }
};
</code></pre><p>You can combine LINQ API methods to carry out multiple actions. Take the following scenario as an example:</p>
<p>We want to find all the people in a list whose address contains "United Kingdom".</p>
<p>To accomplish this, you can utilize a combination of  <code>Where()</code>and <code>Contains()</code>, passing the <code>Contains()</code> function as part of the predicate.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> ukResidents = peopleList.Where(p =&gt; p.Address.Contains(<span class="hljs-string">"United Kingdom"</span>)).ToList();
</code></pre>
<h2 id="heading-deferred-execution">Deferred Execution</h2>
<p>LINQ queries use what's called deferred execution. This means that the query will not be executed immediately when it is defined.</p>
<p>Instead, it is executed when the query results are iterated or when certain operators trigger the execution explicitly. This deferred execution enables optimizations and improves performance by avoiding unnecessary computations.</p>
<p>This goes back to what I discussed earlier with the conversion of <code>IQueryable</code> to another object. For example, a list using <code>.ToList()</code>. It's the <code>ToList()</code>that converts the <code>IQueryable</code> object to a list and actually executes the query.</p>
<p>Lets take a look at an example:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> people = <span class="hljs-keyword">new</span> List&lt;Person&gt;()
{
    <span class="hljs-keyword">new</span>() { Name = <span class="hljs-string">"Harry Potter"</span>, Address = <span class="hljs-string">"123 Privet Drive, Hogwarts, United Kingdom"</span> },
    <span class="hljs-keyword">new</span>() { Name = <span class="hljs-string">"Alex the Kidd"</span>, Address = <span class="hljs-string">"Rock Paper Scissors Avenue, United Kingdom"</span> },
    <span class="hljs-keyword">new</span>() { Name = <span class="hljs-string">"Donkey Kong"</span>, Address = <span class="hljs-string">" The Monkey Temple, Jungle"</span> }
};

<span class="hljs-comment">// then we'll define the query</span>
<span class="hljs-keyword">var</span> peopleCalledHarryPotter = people.Where(x =&gt; x.Name == <span class="hljs-string">"Harry Potter"</span>);

<span class="hljs-comment">// this will create the query object, You could write other code here.</span>

<span class="hljs-comment">// now convert the IQueryable query object to a List, thus invoking the actual query.</span>

<span class="hljs-keyword">var</span> list = peopleCalledHarryPotter.ToList();
</code></pre>
<p>Though a basic example, this demonstrates that you can create a queryable object and execute additional code before actually running the query using the <code>.ToList()</code> extension method.</p>
<h2 id="heading-how-to-chain-iqueryable-api-methods">How to Chain IQueryable API Methods</h2>
<p>Similar to combining <code>Where</code> and <code>Contains</code>, you can further enhance your queries by chaining LINQ API methods. </p>
<p>For example, using <code>Where()</code> and <code>GroupBy()</code> together allows you to filter and then group data by a property. </p>
<p>Let's apply what we've learned and chain these methods. Instead of using <code>.ToList()</code> to create a new variable with the results, we can utilize the query object within a <code>ForEach</code> loop to execute the query and iterate over the results simultaneously.</p>
<p>Update the <code>Person</code> class to have a <code>Age</code> property:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Person</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-keyword">public</span> <span class="hljs-keyword">string</span> Address { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }    
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> Age { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
}
</code></pre>
<p>Then look at the following code, which will first filter the list of people, and then group them based on <code>Age</code>.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;

public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Program</span>
</span>{
    public <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> Main()
    {
        List&lt;Person&gt; people = <span class="hljs-keyword">new</span> List&lt;Person&gt;
        {
            <span class="hljs-keyword">new</span> Person { Name = <span class="hljs-string">"John"</span>, Age = <span class="hljs-number">30</span> },
            <span class="hljs-keyword">new</span> Person { Name = <span class="hljs-string">"Alice"</span>, Age = <span class="hljs-number">25</span> },
            <span class="hljs-keyword">new</span> Person { Name = <span class="hljs-string">"Bob"</span>, Age = <span class="hljs-number">30</span> },
            <span class="hljs-keyword">new</span> Person { Name = <span class="hljs-string">"Charlie"</span>, Age = <span class="hljs-number">25</span> },
            <span class="hljs-keyword">new</span> Person { Name = <span class="hljs-string">"Eve"</span>, Age = <span class="hljs-number">35</span> }
        };

        <span class="hljs-keyword">var</span> groupsOfPeople = people
            .Where(<span class="hljs-function"><span class="hljs-params">p</span> =&gt;</span> p.Age &gt;= <span class="hljs-number">30</span>)  <span class="hljs-comment">// Filter people with age &gt;= 30</span>
            .GroupBy(<span class="hljs-function"><span class="hljs-params">p</span> =&gt;</span> p.Age);    <span class="hljs-comment">// Group people by their age</span>

        foreach (<span class="hljs-keyword">var</span> group <span class="hljs-keyword">in</span> groupsOfPeople)
        {
            Console.WriteLine($<span class="hljs-string">"Age Group: {group.Key}"</span>); <span class="hljs-comment">// output the Age</span>
            foreach (<span class="hljs-keyword">var</span> person <span class="hljs-keyword">in</span> group)
            {
                Console.WriteLine($<span class="hljs-string">"Name: {person.Name}, Age: {person.Age}"</span>);
            }
        }
    }
}
</code></pre><p>This combination of LINQ methods allow us to define more complex quieries without using the Language Level Query Syntax.</p>
<p>Sometimes it can based on personal preference, but I believe the method syntax is much more readable.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, we've explored the power of LINQ in .NET, comparing its language-level query syntax and method syntax. We've demonstrated how to simplify complex queries using LINQ API methods and discussed common methods like <code>OrderBy</code>, <code>First()</code>, <code>Single()</code>, <code>SingleOrDefault()</code>, and <code>Select</code>.</p>
<p>We highlighted the importance of writing defensive code and the concept of deferred execution, which optimizes performance. By combining and chaining LINQ methods, you can create complex, readable queries efficiently.</p>
<p>LINQ is a versatile tool that enhances your ability to handle data in .NET applications. Whether using query syntax or method syntax, LINQ provides a powerful way to write efficient and maintainable code.</p>
<p>You can find some useful examples on the Microsoft website <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/csharp/tutorials/working-with-linq">here</a></p>
<p>As always I'd welcome comments, or discussion on the topic. You can follow me on <a target="_blank" href="https://twitter.com/grantdotdev">Twitter</a> </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Outsmart AI as a Developer [Dr. Chuck Interview #127] ]]>
                </title>
                <description>
                    <![CDATA[ On this week's episode of the podcast, freeCodeCamp founder Quincy Larson interviews Dr. Chuck. He's a software engineer and Computer Science professor at University of Michigan, which has one of the top-ranked CS programs in the world. Dr. Charles "... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-outsmart-ai-as-a-developer-dr-chuck-interview-127/</link>
                <guid isPermaLink="false">6663abb14eb43e9dcabb988a</guid>
                
                    <category>
                        <![CDATA[ podcast ]]>
                    </category>
                
                    <category>
                        <![CDATA[ AI ]]>
                    </category>
                
                    <category>
                        <![CDATA[ learn to code ]]>
                    </category>
                
                    <category>
                        <![CDATA[ C ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Quincy Larson ]]>
                </dc:creator>
                <pubDate>Sat, 08 Jun 2024 00:54:09 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1717808017715/c7c44d08-b140-4171-a679-a201fd31993e.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>On this week's episode of the podcast, freeCodeCamp founder Quincy Larson interviews Dr. Chuck. He's a software engineer and Computer Science professor at University of Michigan, which has one of the top-ranked CS programs in the world.</p>
<p>Dr. Charles "Chuck" Severance is also creator of many popular free learning resources like his Python for Everyone and C for Everyone, which millions of students have taken over the past decade.</p>
<p>We talk about:</p>
<ul>
<li><p>What separates a Master Programmer from an average developer, and how to become one</p>
</li>
<li><p>Dr. Chuck's mission to make programming knowledge freely available</p>
</li>
<li><p>The fundamental shortcomings of how Computer Science is currently taught at universities – even elite universities like the one he's a professor at</p>
</li>
<li><p>Dr. Chuck's theories on recent tech layoffs and what he thinks the near future holds</p>
</li>
<li><p>Dr. Chuck's love of racing $2,500 cars that he revives from the junk yard, and flying planes</p>
</li>
</ul>
<p>Can you guess what song I'm playing on my bass during the intro? It's a 2015 song from an Australian musician.</p>
<p>Be sure to follow The freeCodeCamp podcast in your favorite podcast app. And share this podcast with a friend. Let's inspire more folks to learn to code and build careers for themselves in tech.</p>
<p>Also, I want to thank the 9,331 kind people who support our charity each month, and who make this podcast possible. You can join them and support our mission at: <a target="_blank" href="https://www.freecodecamp.org/donate">https://www.freecodecamp.org/donate</a></p>
<p>You can watch the interview on YouTube:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/skg2XRUMcGQ" 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> </p>
<p>Or you can listen to the podcast in Apple Podcasts, Spotify, or your favorite podcast app. You can also listen to the podcast below, right in your browser:</p>
<div class="embed-wrapper">
        <iframe width="100%" height="152" src="https://open.spotify.com/embed/episode/7EZV9IofaSm9w6ViupHUBy" style="" title="Spotify embed" allow="autoplay; clipboard-write; encrypted-media; fullscreen; picture-in-picture" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<p>Links we talk about during our conversation:</p>
<ul>
<li><p>Dr. Chuck's latest freeCodeCamp course on C programming: <a target="_blank" href="https://www.freecodecamp.org/news/complete-c-programming-course-from-dr-chuck/">https://www.freecodecamp.org/news/complete-c-programming-course-from-dr-chuck/</a></p>
</li>
<li><p>Dr. Chuck's Python for Everyone freeCodeCamp Course: <a target="_blank" href="https://www.freecodecamp.org/news/python-for-everybody/">https://www.freecodecamp.org/news/python-for-everybody/</a></p>
</li>
<li><p>Kylie Ying's popular Machine Learning for Everyone course inspired by Dr. Chuck: <a target="_blank" href="https://www.freecodecamp.org/news/machine-learning-for-everybody/">https://www.freecodecamp.org/news/machine-learning-for-everybody/</a></p>
</li>
<li><p>Dr. Chuck's website with his free interactive coursework: <a target="_blank" href="https://online.dr-chuck.com/">https://online.dr-chuck.com/</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Complete C Programming Course from Dr. Chuck ]]>
                </title>
                <description>
                    <![CDATA[ We just released a comprehensive C course on the freeCodeCamp.org YouTube channel. This course, developed by Dr. Charles Severance (aka Dr. Chuck), is designed to help you understand computer architecture and low-level programming using the classic C... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/complete-c-programming-course-from-dr-chuck/</link>
                <guid isPermaLink="false">66589975b4646539d6571ce4</guid>
                
                    <category>
                        <![CDATA[ C ]]>
                    </category>
                
                    <category>
                        <![CDATA[ youtube ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Beau Carnes ]]>
                </dc:creator>
                <pubDate>Thu, 30 May 2024 15:21:25 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1717003896462/adb98655-0557-4f01-ae93-8c685102e5f2.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>We just released a comprehensive C course on the freeCodeCamp.org YouTube channel. This course, developed by Dr. Charles Severance (aka Dr. Chuck), is designed to help you understand computer architecture and low-level programming using the classic C programming language.</p>
<h1 id="heading-about-the-course">About the Course</h1>
<p>In this comprehensive course, Dr. Chuck uses the classic book "The C Programming Language" by Brian Kernighan and Dennis Ritchie, often referred to as K&amp;R, to guide you through the fundamentals of C. This book, first published in 1978, has been instrumental in shaping modern programming languages and provides a solid foundation for learning C.</p>
<p>Here are the sections in this course:</p>
<ul>
<li><p><strong>K&amp;R 0: Historical Context:</strong> Understand the historical significance of C and its impact on computing.</p>
</li>
<li><p><strong>From Python to C:</strong> Transition smoothly from Python to C, comparing and contrasting the two languages.</p>
</li>
<li><p><strong>K&amp;R 1: A Tutorial Introduction:</strong> Get an introduction to the basics of C programming.</p>
</li>
<li><p><strong>K&amp;R 2: Types, Operators, and Expressions:</strong> Learn about data types, operators, and expressions in C.</p>
</li>
<li><p><strong>K&amp;R 3: Control Flow:</strong> Explore control flow constructs like loops and conditionals.</p>
</li>
<li><p><strong>K&amp;R 4: Functions and Program Structure:</strong> Understand how to structure programs and write functions.</p>
</li>
<li><p><strong>K&amp;R 5: Pointers and Arrays:</strong> Dive deep into pointers and arrays, key concepts in C.</p>
</li>
<li><p><strong>K&amp;R 6: Structures:</strong> Learn about structures and their uses in C programming.</p>
</li>
<li><p><strong>Object-Oriented Programming:</strong> Discover the underpinnings of object-oriented concepts in C-based languages.</p>
</li>
<li><p><strong>Encapsulation and Abstraction:</strong> Improve your understanding of these critical programming principles.</p>
</li>
<li><p><strong>Tree Maps and Hash Maps:</strong> Implement complex data structures.</p>
</li>
<li><p><strong>Epilogue:</strong> Reflect on the journey and the evolution of programming languages.</p>
</li>
</ul>
<p>In the Epilogue of this course, Dr. Chuck interviews Guido van Rossum, the creator of Python, providing unique insights into the development of modern programming languages and their relationship with C.</p>
<h1 id="heading-about-dr-chuck">About Dr. Chuck</h1>
<p>Dr. Charles Severance is a clinical associate professor at the University of Michigan School of Information. Known for his engaging teaching style and deep expertise in programming, Dr. Chuck has made significant contributions to online education. He is the instructor of the popular "Python for Everybody" course series and has authored several influential textbooks.</p>
<h1 id="heading-why-learn-c-in-2024">Why Learn C in 2024?</h1>
<p>Learning C in 2024 can be incredibly beneficial for several reasons:</p>
<ol>
<li><p><strong>Foundational Knowledge:</strong></p>
<ul>
<li><p><strong>Understanding Low-Level Programming:</strong> C provides a deep understanding of how computers work at a low level, including memory management, pointers, and system calls. This knowledge is crucial for grasping how software interacts with hardware.</p>
</li>
<li><p><strong>Strong Foundation for Other Languages:</strong> Many modern programming languages, including C++, Java, and Python, have their roots in C. Learning C can make it easier to pick up these languages and understand their underlying mechanisms.</p>
</li>
</ul>
</li>
<li><p><strong>Performance and Efficiency:</strong></p>
<ul>
<li><p><strong>High Performance:</strong> C is known for its efficiency and performance. It is often used in performance-critical applications, such as operating systems, embedded systems, and game development.</p>
</li>
<li><p><strong>Resource Management:</strong> C allows fine-grained control over system resources, which is essential for writing efficient and optimized code.</p>
</li>
</ul>
</li>
<li><p><strong>System-Level Programming:</strong></p>
<ul>
<li><p><strong>Operating Systems and Kernels:</strong> C is the language of choice for developing operating systems and kernels. Learning C is essential if you are interested in systems programming or contributing to open-source projects like Linux.</p>
</li>
<li><p><strong>Embedded Systems:</strong> C is widely used in embedded systems programming. If you are interested in developing firmware or working with microcontrollers, C is a must-know language.</p>
</li>
</ul>
</li>
<li><p><strong>Career Opportunities:</strong></p>
<ul>
<li><p><strong>Job Market Demand:</strong> C remains in demand in various industries, including systems programming, embedded systems, telecommunications, and game development.</p>
</li>
<li><p><strong>Versatility:</strong> Knowledge of C can open doors to various career paths, from software development to cybersecurity and beyond.</p>
</li>
</ul>
</li>
<li><p><strong>Legacy Systems:</strong></p>
<ul>
<li><p><strong>Maintenance of Existing Codebases:</strong> Many legacy systems and critical software are written in C. Understanding C can be crucial for maintaining and updating these systems.</p>
</li>
<li><p><strong>Interoperability:</strong> C code is often integrated with other languages and systems. Knowing C can help you work on projects that require interfacing with existing C codebases.</p>
</li>
</ul>
</li>
<li><p><strong>Educational Value:</strong></p>
<ul>
<li><p><strong>Algorithm and Data Structure Implementation:</strong> C is excellent for learning and implementing fundamental algorithms and data structures. This experience can enhance your problem-solving skills and algorithmic thinking.</p>
</li>
<li><p><strong>Understanding Computer Science Concepts:</strong> C is often used in academic settings to teach core computer science concepts, such as operating systems, compilers, and networking.</p>
</li>
</ul>
</li>
</ol>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Whether you're a beginner looking to grasp the basics of C or an experienced programmer wanting to refresh your knowledge, this course is perfect for you. Watch the full course <a target="_blank" href="https://youtu.be/PaPN51Mm5qQ">on the freeCodeCamp.org YouTube channel</a> (19-hour watch).</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/PaPN51Mm5qQ" 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>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Object-Oriented Programming in C# – Explained With Examples ]]>
                </title>
                <description>
                    <![CDATA[ Welcome to this comprehensive guide on object-oriented programming (OOP) using C#. This article will delve into the four fundamental pillars of OOP: Inheritance Encapsulation Polymorphism Abstraction Whether you're a seasoned programmer or a beginn... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-oop-in-c-sharp/</link>
                <guid isPermaLink="false">66bb570129aa951a4c0628b9</guid>
                
                    <category>
                        <![CDATA[ C ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Object Oriented Programming ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Isaiah Clifford Opoku ]]>
                </dc:creator>
                <pubDate>Wed, 01 May 2024 12:14:44 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/04/Attractive-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Welcome to this comprehensive guide on object-oriented programming (OOP) using C#. This article will delve into the four fundamental pillars of OOP:</p>
<ul>
<li>Inheritance</li>
<li>Encapsulation</li>
<li>Polymorphism</li>
<li>Abstraction</li>
</ul>
<p>Whether you're a seasoned programmer or a beginner stepping into the world of C#, this article aims to enhance your understanding of OOP concepts and their implementation in C#. </p>
<p>If you're new to C#, consider taking the free certification course on <a target="_blank" href="https://www.freecodecamp.org/learn/foundational-c-sharp-with-microsoft/">freeCodeCamp</a> or the free course on <a target="_blank" href="https://learn.microsoft.com/en-us/courses/browse/?term=c%23&amp;resource_type=learning%20path">Microsoft Learn</a> to familiarize yourself with the language.</p>
<p>Remember, the principles of OOP are universal and apply to most object-oriented programming languages. Therefore, the knowledge you gain from this article can be applied to learning OOP in any language.</p>
<p>Let's get started!</p>
<h1 id="heading-table-of-contents">Table of Contents</h1>
<ol start="2">
<li><p><a class="post-section-overview" href="#heading-what-is-object-oriented-programming-oop">What is Object-Oriented Programming (OOP)</a></p>
</li>
<li><p><a class="post-section-overview" href="#why-use-object-oriented-programming">Why Use Object-Oriented Programming?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-four-pillars-of-object-oriented-programming">The Four Pillars of Object-Oriented Programming</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-inheritance">Inheritance</a></p>
</li>
<li><p><a class="post-section-overview" href="#types-of-inheritance">Types of Inheritance</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-encapsulation">Encapsulation</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-polymorphism">Polymorphism</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-abstraction">Abstraction</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-summary">Summary</a></p>
</li>
</ol>
<h1 id="what-is-object-oriented-programming-oop">What is Object-Oriented Programming (OOP)</h1>

<p>Object-Oriented Programming (OOP) is a programming paradigm that uses <code>objects</code> and <code>classes</code> to design and develop software applications. It is based on the concept of objects, which can contain data in the form of fields (attributes or properties) and code in the form of procedures (methods or functions).</p>
<p>Object-Oriented Programming offers several benefits, including:</p>
<ul>
<li><p><strong>Modularity</strong>: OOP promotes modularity by breaking down complex systems into smaller, manageable parts (objects). This makes it easier to maintain and update the code.</p>
</li>
<li><p><strong>Reusability</strong>: OOP allows you to reuse existing code by creating new objects based on existing ones. This saves time and effort in developing new applications.</p>
</li>
<li><p><strong>Flexibility</strong>: OOP provides flexibility in designing and implementing software systems. You can easily modify and extend the functionality of objects without affecting other parts of the system.</p>
</li>
<li><p><strong>Scalability</strong>: OOP supports scalability by allowing you to add new objects and classes as the system grows. This makes it easier to accommodate changes and enhancements in the software.</p>
</li>
</ul>
<p>As you can see, OOP offers several advantages that makes it a popular choice for developing software applications. Let's explore the four fundamental pillars of OOP in more detail.</p>
<h1 id="the-four-pillars-of-object-oriented-programming">The Four Pillars of Object-Oriented Programming</h1>

<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/Add-a-heading.png" alt="Add-a-heading" width="600" height="400" loading="lazy"></p>
<p>The four pillars of Object-Oriented Programming are: </p>
<ol>
<li><strong>Inheritance</strong></li>
<li><strong>Encapsulation</strong></li>
<li><strong>Polymorphism</strong></li>
<li><strong>Abstraction</strong></li>
</ol>
<p>These pillars form the foundation of OOP and are essential concepts to understand when working with object-oriented programming languages like C#.</p>
<p>Let go deep into each of the pillars of OOP in the next sections.</p>
<p>Let's start with the first pillar of OOP: <code>Inheritance</code>.</p>
<h1 id="inheritance">Inheritance</h1>

<p>Inheritance is a concept used in most programming languages and is something you can't avoid when working with object-oriented programming. Programming languages like <code>C#</code> and Java are some of the languages that support inheritance. In this article, we will be looking at inheritance in <code>C#</code> and how to use it in your application.</p>
<h4 id="heading-what-is-inheritance">What is Inheritance?</h4>
<p>Imagine that you have a family tree, where each generation represents a class in C#. The first generation is the <code>base class</code>, which is the foundational class that provides the basic structure and properties. This could be likened to the patriarch of the family, who establishes the family's core values and characteristics.</p>
<p>As the family tree progresses, each subsequent generation inherits the traits and characteristics of the previous generation but also adds or modifies them to reflect their unique identity. These subsequent generations can be thought of as <code>derived</code> classes in C#, which inherit from the <code>base</code> class but also introduce their own unique features or modifications.</p>
<p>For example, the patriarch might have established the family's love for gardening, which becomes a fundamental trait passed down through the generations. However, as the family tree evolves, some members might develop a special interest in growing exotic plants, while others might focus on organic gardening. These special interests represent the unique characteristics of the derived classes, which inherit the basic love for gardening from the base class but also introduce their own unique features.</p>
<p>In this analogy, the <code>base</code> class is the patriarch, which represents the foundational class with its basic properties and characteristics. The <code>derived</code> classes are the subsequent generations, each with their unique features or modifications, inheriting the basic traits from the base class but also adding their own unique aspects. This process of inheritance allows for the creation of a rich and varied family tree, where each generation builds upon the previous one, introducing new traits and refining existing ones.</p>
<p>Inheritance is a mechanism that allows you to define a new <code>class</code> based on an existing <code>class</code>. The new class inherits all the members (fields, properties, and methods) of the existing class. The existing class is known as the <code>base</code> class, and the new class is known as the <code>derived</code> class.</p>
<p>Basic Syntax of inheritance in C#:</p>
<pre><code class="lang-csharp">
<span class="hljs-keyword">class</span> <span class="hljs-title">BaseClass</span>
{
    <span class="hljs-comment">// Base class members</span>
}

<span class="hljs-keyword">class</span> <span class="hljs-title">DerivedClass</span> : <span class="hljs-title">BaseClass</span>
{
    <span class="hljs-comment">// Derived class members</span>
}
</code></pre>
<p>In the above code snippet, <code>BaseClass</code> is the base class, and <code>DerivedClass</code> is the derived class. The <code>DerivedClass</code> inherits all the members of the <code>BaseClass</code>. The colon <code>(:)</code> is used to indicate that the <code>DerivedClass</code> is derived from the <code>BaseClass</code>.</p>
<p>If You are new to <code>C#</code> and you don't know what a class is, don't worry, I will explain it to you. A class is a blueprint for creating objects. It defines the properties and methods that an object of the class will have. Here is an example of a class in <code>C#</code>:</p>
<pre><code class="lang-csharp">
<span class="hljs-keyword">class</span> <span class="hljs-title">Person</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-keyword">public</span> <span class="hljs-keyword">int</span> Age { <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-keyword">void</span> <span class="hljs-title">Display</span>(<span class="hljs-params"></span>)</span>
    {
        Console.WriteLine(<span class="hljs-string">$"Name: <span class="hljs-subst">{Name}</span>, Age: <span class="hljs-subst">{Age}</span>"</span>);
    }
}
</code></pre>
<p>In the above code snippet, the <code>Person</code> class has two properties (<code>Name</code> and <code>Age</code>) and a method (<code>Display</code>). The properties represent the state of the object, and the method represents the behavior of the object. You can create an object of the <code>Person</code> class and set its properties like this:</p>
<pre><code class="lang-csharp">
Person person = <span class="hljs-keyword">new</span> Person();
person.Name = <span class="hljs-string">"John"</span>;
person.Age = <span class="hljs-number">30</span>;
</code></pre>
<p>You can call the <code>Display</code> method on the <code>person</code> object to display the name and age of the person:</p>
<pre><code class="lang-csharp">
person.Display(); <span class="hljs-comment">// Output: Name: John, Age: 30</span>
</code></pre>
<p>Before moving on with the article, let's look at some keywords you're going to come across  a lot <code>base class</code>, <code>Abstract class</code> ,<code>derived class</code>, <code>parent class</code>, and <code>child class</code>.</p>
<p>Let me explain them to you.</p>
<ul>
<li><strong>Base class</strong>: This is the class whose members are inherited by another class. It is also known as the parent class.</li>
</ul>
<pre><code class="lang-csharp">
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">BaseClass</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Display</span>(<span class="hljs-params"></span>)</span>
    {
        Console.WriteLine(<span class="hljs-string">"This is a base class"</span>);
    }
}
</code></pre>
<ul>
<li><strong>Abstract class</strong>: This is a class that cannot be instantiated. It is used to provide a common base for all the derived classes. It can contain both abstract and non-abstract methods.</li>
</ul>
<pre><code class="lang-csharp">
<span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">class</span> <span class="hljs-title">AbstractClass</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Display</span>(<span class="hljs-params"></span>)</span>;
}
</code></pre>
<ul>
<li><strong>Derived class</strong>: This is the class that inherits the members of the base class. It is also known as the child class.</li>
</ul>
<pre><code class="lang-csharp">
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">DerivedClass</span> : <span class="hljs-title">BaseClass</span>

{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Show</span>(<span class="hljs-params"></span>)</span>
    {
        Console.WriteLine(<span class="hljs-string">"This is a derived class"</span>);
    }
}
</code></pre>
<p> So now you know what these keywords mean, let's move on to the next section.</p>
<h4 id="heading-types-of-inheritance">Types of Inheritance</h4>
<p>Inheritance can be classified into different types based on the way the classes are derived. The following are the types of inheritance: </p>
<ul>
<li><strong>Single Inheritance</strong>: Single inheritance is a fundamental concept in object-oriented programming where a class, known as the <code>derived class</code>, is based on another class, known as the <code>base class</code>. This is the simplest form of inheritance. </li>
</ul>
<p>To illustrate this, let's consider a real-world analogy. Imagine you are the only child of your father. In this scenario, you inherit characteristics from your father. This is akin to single inheritance in programming.</p>
<p>Let's look at an example in <code>C#</code>:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Father</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Display</span>(<span class="hljs-params"></span>)</span>
    {
        Console.WriteLine(<span class="hljs-string">"This is the father class"</span>);
    }
}
</code></pre>
<p>In the above code, <code>Father</code> is the base class with a method <code>Display</code>.</p>
<p>Now, let's create a derived class <code>Child</code> that inherits from the <code>Father</code> class:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Child</span> : <span class="hljs-title">Father</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Show</span>(<span class="hljs-params"></span>)</span>
    {
        Console.WriteLine(<span class="hljs-string">"This is the child class"</span>);
    }
}
</code></pre>
<p>In this code snippet, the <code>Child</code> class is derived from the <code>Father</code> class. The <code>Child</code> class inherits the <code>Display</code> method from the <code>Father</code> class. </p>
<p>You can create an object of the <code>Child</code> class and call the <code>Display</code> method. This demonstrates that the <code>Child</code> class can access the <code>Display</code> method from the <code>Father</code> class.</p>
<pre><code class="lang-csharp">Child child = <span class="hljs-keyword">new</span> Child();
child.Display(); <span class="hljs-comment">// Output: This is the father class</span>
</code></pre>
<ul>
<li><strong>Multilevel Inheritance</strong>: Multilevel inheritance is a concept in object-oriented programming where a class is derived from another derived class, creating a chain of inheritance.</li>
</ul>
<p>To better understand this, let's consider a family tree analogy. Assuming you are the <code>child</code> of your <code>father</code>, and your <code>father</code> is the <code>child</code> of your <code>grandfather</code>. In this scenario, you inherit characteristics from both your father and grandfather. This is similar to multilevel inheritance in programming.</p>
<p>Let's explore this concept with an example in <code>C#</code>:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Grandfather</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Display</span>(<span class="hljs-params"></span>)</span>
    {
        Console.WriteLine(<span class="hljs-string">"This is the grandfather class"</span>);
    }
}
</code></pre>
<p>In the above code, <code>Grandfather</code> is the base class with a method <code>Display</code>.</p>
<p>Next, we created a derived class <code>Father</code> that inherits from the <code>Grandfather</code> class:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Father</span> : <span class="hljs-title">Grandfather</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Show</span>(<span class="hljs-params"></span>)</span>
    {
        Console.WriteLine(<span class="hljs-string">"This is the father class"</span>);
    }
}
</code></pre>
<p>Here, the <code>Father</code> class is derived from the <code>Grandfather</code> class and inherits the <code>Display</code> method from it.</p>
<p>Finally, we created another derived class <code>Child</code> that inherits from the <code>Father</code> class:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Child</span> : <span class="hljs-title">Father</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">DisplayChild</span>(<span class="hljs-params"></span>)</span>
    {
        Console.WriteLine(<span class="hljs-string">"This is the child class"</span>);
    }
}
</code></pre>
<p>In this code snippet, the <code>Child</code> class is derived from the <code>Father</code> class. The <code>Child</code> class inherits the <code>Display</code> and <code>Show</code> methods from the <code>Father</code> class.</p>
<p>We can create an object of the <code>Child</code> class and call the <code>Display</code> and <code>Show</code> methods. This demonstrates that the <code>Child</code> class can access the <code>Display</code> and <code>Show</code> methods from the <code>Father</code> class.</p>
<pre><code class="lang-csharp">Child child = <span class="hljs-keyword">new</span> Child();
child.Display(); <span class="hljs-comment">// Output: This is the grandfather class</span>
child.Show(); <span class="hljs-comment">// Output: This is the father class</span>
child.DisplayChild(); <span class="hljs-comment">// Output: This is the child class</span>
</code></pre>
<ul>
<li><strong>Hierarchical Inheritance</strong>: Hierarchical inheritance is a concept in object-oriented programming where multiple classes are derived from a <code>single base class</code>, forming a <code>tree-like structure</code>.</li>
</ul>
<p>To illustrate this, let's consider a real-world analogy. Assuming you and your <code>siblings</code> share the <code>same parent</code>. In this scenario, all of you inherit characteristics from the same parent. This is akin to hierarchical inheritance in programming.</p>
<p>Let's explore this concept with an example in <code>C#</code>:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Parent</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Display</span>(<span class="hljs-params"></span>)</span>
    {
        Console.WriteLine(<span class="hljs-string">"This is the parent class"</span>);
    }
}
</code></pre>
<p>In the above code, <code>Parent</code> is the base class with a method <code>Display</code>.</p>
<p> Next, we created two derived classes <code>Child1</code> and <code>Child2</code> that inherit from the <code>Parent</code> class:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Child1</span> : <span class="hljs-title">Parent</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Show1</span>(<span class="hljs-params"></span>)</span>
    {
        Console.WriteLine(<span class="hljs-string">"This is the first child class"</span>);
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Child2</span> : <span class="hljs-title">Parent</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Show2</span>(<span class="hljs-params"></span>)</span>
    {
        Console.WriteLine(<span class="hljs-string">"This is the second child class"</span>);
    }
}
</code></pre>
<p>In this code snippet, the <code>Child1</code> and <code>Child2</code> classes are derived from the <code>Parent</code> class. Both classes inherit the <code>Display</code> method from the <code>Parent</code> class.</p>
<p>We can create objects of the <code>Child1</code> and <code>Child2</code> classes and call the <code>Display</code>, <code>Show1</code>, and <code>Show2</code> methods. This demonstrates that both <code>Child1</code> and <code>Child2</code> classes can access the <code>Display</code> method from the <code>Parent</code> class.</p>
<pre><code class="lang-csharp">Child1 child1 = <span class="hljs-keyword">new</span> Child1();
child1.Display(); <span class="hljs-comment">// Output: This is the parent class</span>
child1.Show1(); <span class="hljs-comment">// Output: This is the first child class</span>

Child2 child2 = <span class="hljs-keyword">new</span> Child2();
child2.Display(); <span class="hljs-comment">// Output: This is the parent class</span>
child2.Show2(); <span class="hljs-comment">// Output: This is the second child class</span>
</code></pre>
<p>Congratulation you have learned the basics of inheritance in C#, let's move to the next section <code>Encapsulation</code>.</p>
<h4 id="heading-understanding-encapsulation-and-properties-in-c">Understanding Encapsulation and Properties in C</h4>
<p>As we continue our journey through the pillars of OOP, we now arrive at <code>Encapsulation</code>. Before we delve into <code>Encapsulation</code>, it's crucial to understand a common concept in C# called <code>properties</code>.</p>
<p>Properties in C# are members of a class that provide a flexible mechanism to read, write, or compute the value of a private field. They can be used as if they are public data members, but they are actually special methods called accessors. These accessors are used to get and set the values of private fields.</p>
<p>If you're new to this concept, don't worry. Let's break it down with an example:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Person</span>
{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">string</span> name;

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Name
    {
        <span class="hljs-keyword">get</span> { <span class="hljs-keyword">return</span> name; }
        <span class="hljs-keyword">set</span> { name = <span class="hljs-keyword">value</span>; }
    }
}
</code></pre>
<p>In the above code snippet, the <code>Person</code> class has a private field <code>name</code> and a property <code>Name</code>. The property <code>Name</code> has two accessors: a <code>get</code> accessor to retrieve the value of the <code>name</code> field, and a <code>set</code> accessor to set the value of the <code>name</code> field.</p>
<p>Understanding properties is key to grasping the concept of <code>Encapsulation</code>, which we will explore in the next section. </p>
<h1 id="encapsulation">Encapsulation</h1>

<p>To understand <code>Encapsulation</code>, let's use an analogy. Consider a <code>gift box</code> that contains a <code>gift</code>. The <code>gift box</code> acts as a container that encapsulates the <code>gift</code>. The <code>gift</code> is hidden from the outside world and can only be accessed through the <code>gift box</code>. This is akin to <code>Encapsulation</code> in object-oriented programming.</p>
<p><code>Encapsulation</code> is the principle of bundling the data (fields) and methods (functions) that operate on the data into a single unit, known as a <code>class</code>. It restricts direct access to some of an object's components and allows access only through the methods of the class. In essence, <code>Encapsulation</code> conceals the internal state of an object and only exposes the necessary information to the outside world.</p>
<p>Let's see an example in C#:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Person</span>
{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">string</span> name;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> age;

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Name
    {
        <span class="hljs-keyword">get</span> { <span class="hljs-keyword">return</span> name; }
        <span class="hljs-keyword">set</span> { name = <span class="hljs-keyword">value</span>; }
    }

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> Age
    {
        <span class="hljs-keyword">get</span> { <span class="hljs-keyword">return</span> age; }
        <span class="hljs-keyword">set</span> { age = <span class="hljs-keyword">value</span>; }
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Display</span>(<span class="hljs-params"></span>)</span>
    {
        Console.WriteLine(<span class="hljs-string">$"Name: <span class="hljs-subst">{Name}</span>, Age: <span class="hljs-subst">{Age}</span>"</span>);
    }
}
</code></pre>
<p>In the above code snippet, the <code>Person</code> class encapsulates the data (fields <code>name</code> and <code>age</code>) and methods (<code>Display</code>) into a single unit. The fields <code>name</code> and <code>age</code> are private, meaning they cannot be accessed directly from outside the class. The properties <code>Name</code> and <code>Age</code> provide controlled access to the private fields using <code>get</code> and <code>set</code> accessors.</p>
<p>Let's add another example to further illustrate this concept:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">BankAccount</span>
{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">double</span> balance;

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">double</span> Balance
    {
        <span class="hljs-keyword">get</span> { <span class="hljs-keyword">return</span> balance; }
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">set</span> { balance = <span class="hljs-keyword">value</span>; }
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Deposit</span>(<span class="hljs-params"><span class="hljs-keyword">double</span> amount</span>)</span>
    {
        <span class="hljs-keyword">if</span> (amount &gt; <span class="hljs-number">0</span>)
        {
            Balance += amount;
        }
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Withdraw</span>(<span class="hljs-params"><span class="hljs-keyword">double</span> amount</span>)</span>
    {
        <span class="hljs-keyword">if</span> (amount &gt; <span class="hljs-number">0</span> &amp;&amp; Balance &gt;= amount)
        {
            Balance -= amount;
        }
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">DisplayBalance</span>(<span class="hljs-params"></span>)</span>
    {
        Console.WriteLine(<span class="hljs-string">$"Balance: <span class="hljs-subst">{Balance}</span>"</span>);
    }
}
</code></pre>
<p>In this example, the <code>BankAccount</code> class encapsulates the <code>balance</code> field and the methods that operate on it (<code>Deposit</code>, <code>Withdraw</code>, <code>DisplayBalance</code>). The <code>balance</code> field is private and can only be accessed through the <code>Balance</code> property and the methods of the class. This ensures that the balance cannot be directly manipulated from outside the class, providing a secure way to manage a bank account.</p>
<p>Congratulations! You have learned about <code>Encapsulation</code> and how it is implemented in C#. Let's move on to the next section, <code>Polymorphism</code>.</p>
<h4 id="heading-understanding-polymorphism-in-c">Understanding Polymorphism in C</h4>
<p>As we delve deeper into the four pillars of OOP, we now encounter <code>Polymorphism</code>. The term <code>Polymorphism</code> originates from the Greek words <code>poly</code> (many) and <code>morphos</code> (forms), signifying "many forms". In the realm of object-oriented programming, <code>Polymorphism</code> denotes an object's ability to assume multiple forms.</p>
<p>To comprehend <code>Polymorphism</code>, let's consider a <code>music player</code>. It can play various types of music files, such as <code>MP3</code>, <code>WAV</code>, or <code>AAC</code>. Each of these file types is different, yet our music player can handle all of them. This is akin to <code>Polymorphism</code> in object-oriented programming.</p>
<h1 id="polymorphism">Polymorphism</h1>

<p><code>Polymorphism</code> is a core concept in object-oriented programming that allows objects of different classes to be treated as objects of a common superclass. It provides a single interface to represent multiple underlying forms (classes) and enables objects to be processed in a generic manner.</p>
<p>In C#, there are two types of <code>Polymorphism</code>:</p>
<ol>
<li><strong>Compile-time Polymorphism (Method Overloading)</strong></li>
<li><strong>Run-time Polymorphism (Method Overriding)</strong></li>
</ol>
<h3 id="heading-compile-time-polymorphism-method-overloading">Compile-time Polymorphism (Method Overloading)</h3>
<p><code>Compile-time Polymorphism</code>, also known as <code>Method Overloading</code>, allows a class to have multiple methods with the same name but different parameters. The compiler determines which method to invoke based on the number and types of arguments.</p>
<p>Here's an example of <code>Method Overloading</code> in C#:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Printer</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Print</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> message</span>)</span>
    {
        Console.WriteLine(<span class="hljs-string">$"Printing string: <span class="hljs-subst">{message}</span>"</span>);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Print</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> number</span>)</span>
    {
        Console.WriteLine(<span class="hljs-string">$"Printing number: <span class="hljs-subst">{number}</span>"</span>);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Print</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> message, <span class="hljs-keyword">int</span> copies</span>)</span>
    {
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; copies; i++)
        {
            Console.WriteLine(<span class="hljs-string">$"Printing string: <span class="hljs-subst">{message}</span>"</span>);
        }
    }
}
</code></pre>
<p>In this example, the <code>Printer</code> class has three <code>Print</code> methods with the same name but different parameters. This is an example of <code>Method Overloading</code> in C#.</p>
<h3 id="heading-run-time-polymorphism-method-overriding">Run-time Polymorphism (Method Overriding)</h3>
<p><code>Run-time Polymorphism</code>, also known as <code>Method Overriding</code>, allows a subclass to provide a specific implementation of a method that is already provided by its superclass.</p>
<p>Here's an example of <code>Method Overriding</code> in C#:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">MusicPlayer</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">virtual</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Play</span>(<span class="hljs-params"></span>)</span>
    {
        Console.WriteLine(<span class="hljs-string">"Playing music"</span>);
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Mp3Player</span> : <span class="hljs-title">MusicPlayer</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Play</span>(<span class="hljs-params"></span>)</span>
    {
        Console.WriteLine(<span class="hljs-string">"Playing MP3 music"</span>);
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">WavPlayer</span> : <span class="hljs-title">MusicPlayer</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Play</span>(<span class="hljs-params"></span>)</span>
    {
        Console.WriteLine(<span class="hljs-string">"Playing WAV music"</span>);
    }
}
</code></pre>
<p>In this example, the <code>MusicPlayer</code> class has a virtual method <code>Play</code>. The <code>Mp3Player</code> and <code>WavPlayer</code> classes override the <code>Play</code> method with specific implementations for playing MP3 and WAV music, respectively. This is an example of <code>Method Overriding</code> in C#.</p>
<p>Let's see how <code>Polymorphism</code> can be used in a program:</p>
<pre><code class="lang-csharp">MusicPlayer player = <span class="hljs-keyword">new</span> Mp3Player();
player.Play(); <span class="hljs-comment">// Output: Playing MP3 music</span>

player = <span class="hljs-keyword">new</span> WavPlayer();
player.Play(); <span class="hljs-comment">// Output: Playing WAV music</span>
</code></pre>
<p>In this code snippet, we created an object of the <code>Mp3Player</code> class and assigned it to a variable of type <code>MusicPlayer</code>. We then called the <code>Play</code> method on the <code>player</code> object, which invokes the overridden <code>Play</code> method in the <code>Mp3Player</code> class. We then created an object of the <code>WavPlayer</code> class and assigned it to the <code>player</code> variable. When we call the <code>Play</code> method again, it invokes the overridden <code>Play</code> method in the <code>WavPlayer</code> class.</p>
<p>Congratulations! You have learned about <code>Polymorphism</code> and how it is implemented in C#. Let's move on to the final pillar of OOP, <code>Abstraction</code>.</p>
<h4 id="heading-understanding-abstraction-in-c">Understanding Abstraction in C</h4>
<p>As we delve into the final pillar of OOP, we encounter <code>Abstraction</code>. <code>Abstraction</code> is the process of hiding complex implementation details and exposing only the essential features of an object. It emphasizes on what an object does rather than how it does it.</p>
<p>To comprehend <code>Abstraction</code>, let's consider a <code>smartphone</code>. When you use a smartphone, you don't need to understand the intricacies of how the internal components like the <code>processor</code> or the <code>memory</code> work. You only need to know how to interact with the user interface to make calls, send messages, or use apps. This is akin to <code>Abstraction</code> in object-oriented programming.</p>
<h2 id="abstraction">Abstraction</h2>

<p><code>Abstraction</code> is a key concept in object-oriented programming that allows you to create a blueprint for a class with some abstract methods that must be implemented by the derived classes. It enables you to define the structure of a class without providing the implementation details.</p>
<p>In C#, <code>Abstraction</code> can be achieved using <code>abstract</code> classes and <code>interfaces</code>. Let's explore both concepts:</p>
<h3 id="heading-abstract-classes">Abstract Classes</h3>
<p>An <code>abstract class</code> is a class that cannot be instantiated and can contain both abstract and non-abstract methods. An abstract method is a method without a body that must be implemented by the derived classes.</p>
<p>Here's an example of an <code>abstract class</code> in C#:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Speak</span>(<span class="hljs-params"></span>)</span>;
}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> : <span class="hljs-title">Animal</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Speak</span>(<span class="hljs-params"></span>)</span>
    {
        Console.WriteLine(<span class="hljs-string">"The dog barks"</span>);
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Cat</span> : <span class="hljs-title">Animal</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Speak</span>(<span class="hljs-params"></span>)</span>
    {
        Console.WriteLine(<span class="hljs-string">"The cat meows"</span>);
    }
}
</code></pre>
<p>In this example, the <code>Animal</code> class is an abstract class with an abstract method <code>Speak</code>. The <code>Dog</code> and <code>Cat</code> classes inherit from the <code>Animal</code> class and provide specific implementations for the <code>Speak</code> method. This is an example of <code>Abstraction</code> using abstract classes in C#.</p>
<h3 id="heading-interfaces">Interfaces</h3>
<p>An <code>interface</code> is a reference type in C# that defines a contract for classes to implement. It contains only the declaration of the methods, properties, events, or indexers, without providing the implementation.</p>
<p>Here's an example of an <code>interface</code> in C#:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">IFlyable</span>
{
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">Fly</span>(<span class="hljs-params"></span>)</span>;
}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Bird</span> : <span class="hljs-title">IFlyable</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Fly</span>(<span class="hljs-params"></span>)</span>
    {
        Console.WriteLine(<span class="hljs-string">"The bird flies"</span>);
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Airplane</span> : <span class="hljs-title">IFlyable</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Fly</span>(<span class="hljs-params"></span>)</span>
    {
        Console.WriteLine(<span class="hljs-string">"The airplane flies"</span>);
    }
}
</code></pre>
<p>In this example, the <code>IFlyable</code> interface defines a contract with a method <code>Fly</code>. The <code>Bird</code> and <code>Airplane</code> classes implement the <code>IFlyable</code> interface and provide specific implementations for the <code>Fly</code> method. This is an example of <code>Abstraction</code> using interfaces in C#.</p>
<p>Congratulations! You have now learned about <code>Abstraction</code> and how it is implemented in C#. The key takeaway is that <code>Abstraction</code> allows us to hide the complexity of the system and expose only the necessary details to the user.</p>
<h1 id="summary">Summary</h1>

<p>In this article, we have explored the four fundamental pillars of object-oriented programming (OOP) in C#: <code>Inheritance</code>, <code>Encapsulation</code>, <code>Polymorphism</code>, and <code>Abstraction</code>. </p>
<p>These pillars form the foundation of OOP and are essential concepts to understand when working with object-oriented programming languages like C#. The knowledge gained from this article will help you enhance your understanding of OOP concepts and their implementation in C#. </p>
<p>Thank you for reading this article, I hope you find it helpful. If you have any questions or feedback, feel free to reach out to me. Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ C Print String – How to Print a String in C ]]>
                </title>
                <description>
                    <![CDATA[ Printing strings is a fundamental operation in programming. It helps you output information, inspect and debug your code, and display prompts to users. In this article, you will learn some of the different techniques to print strings in C. What is a ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-print-a-string-in-c/</link>
                <guid isPermaLink="false">661fd38bd486669f99451ce9</guid>
                
                    <category>
                        <![CDATA[ c programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ C ]]>
                    </category>
                
                    <category>
                        <![CDATA[ string ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Dionysia Lemonaki ]]>
                </dc:creator>
                <pubDate>Wed, 17 Apr 2024 13:50:03 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/Hcfwew744z4/upload/73cd11d4c62fcaa9d6fa85514d7cb732.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Printing strings is a fundamental operation in programming. It helps you output information, inspect and debug your code, and display prompts to users.</p>
<p>In this article, you will learn some of the different techniques to print strings in C.</p>
<h2 id="heading-what-is-a-string-in-c">What is a String in C?</h2>
<p>A string is a sequence of characters, like letters, numbers, or symbols, that are grouped together. It is used to represent text in programs.</p>
<p>Strings are not a built-in data type in C. Instead, they are represented as arrays of characters, terminated with a special character called the null terminator, <code>\0</code>.</p>
<p>Here is an example of how to create a string in C:</p>
<pre><code class="lang-c"><span class="hljs-keyword">char</span> greeting[] = <span class="hljs-string">"Hello world!"</span>;
</code></pre>
<p>In the code above, I declared a character array named <code>greeting</code>, and initialized it with the string <code>Hello world!</code> enclosed within double quotes, <code>" "</code>.</p>
<p>The C compiler automatically includes the null terminator, <code>\0</code>, at the end of <code>Hello world!</code>.</p>
<h2 id="heading-how-to-print-a-string-in-c-using-the-printf-function">How to Print a String in C Using the <code>printf()</code> Function</h2>
<p>The <code>printf()</code> function is one of the most commonly used ways of printing strings in C.</p>
<p>It stands for "print formatted", and belongs to the standard input/output library, <code>stdio.h</code>. So, in order to use it, you need to first include the <code>stdio.h</code> header file at the beginning of your program.</p>
<p>Let’s take the following example:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
  <span class="hljs-keyword">char</span> greeting[] = <span class="hljs-string">"Hello world!"</span>;

  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%s\n"</span>, greeting);
}

<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// Hello world!</span>
</code></pre>
<p>In the example above, I first included the <code>stdio.h</code> header file at the beginning of my program, which contains the declaration of the <code>printf()</code> function.</p>
<p>Next, I declared a character array named <code>greeting</code> and initialized it with the text <code>Hello world!</code> wrapped in double quotes.</p>
<p>Lastly, I used the <code>printf()</code> function to print the text <code>Hello world!</code>.</p>
<p>When printing a string using the <code>printf()</code> function, you need to use a format specifier.</p>
<p>A format specifier acts as a placeholder that tells the <code>printf()</code> function how to format and print specific types of data. They begin with a percent sign <code>%</code>, followed by a character that specifies the type of data to be formatted. The format specifier for strings is <code>%s</code>.</p>
<p>So, in the line <code>printf("%s\n", greeting);</code>, the <code>%s</code> format specifier tells <code>printf()</code> to print the string stored in the <code>greeting</code> variable followed by a newline character, <code>\n</code>.</p>
<p>Note that the <code>%s</code> format specifier doesn’t include the null terminator, <code>\0,</code> when printing strings. It prints the characters in the string until it encounters it.</p>
<h2 id="heading-how-to-print-a-string-in-c-using-the-puts-function">How to Print a String in C Using the <code>puts()</code> Function</h2>
<p>Another function used for printing strings is <code>puts()</code>.</p>
<p>Let’s take the following example:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
  <span class="hljs-keyword">char</span> greeting[] = <span class="hljs-string">"Hello world!"</span>;

  <span class="hljs-built_in">puts</span>(greeting);
}

<span class="hljs-comment">// Output</span>
<span class="hljs-comment">// Hello world!</span>
</code></pre>
<p>In the example above, I first included the <code>stdio.h</code> header file which contains the <code>puts()</code> declaration.</p>
<p>Then, I declared a character array and initialized it with the text <code>Hello world!</code>. The string automatically ends with the null terminator, <code>\0</code>.</p>
<p>Lastly, I used the <code>puts()</code> function to print the string to the console and passed the string variable <code>greeting</code> as an argument.</p>
<p>The <code>puts()</code> function automatically adds a newline character, <code>\n</code>, at the end of the string.</p>
<p>Note that the <code>puts()</code> function is used to print null-terminated strings. A null-terminated string is a sequence of characters stored in memory followed by a character called the null terminator <code>\0</code>.</p>
<p>So far, all the examples have used only null-terminated strings, such as <code>char greeting[] = "Hello world!";</code>. In memory, it would be represented as <code>['H', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd', '!', '\0']</code>.</p>
<p>Creating non-null-terminated strings intentionally is not common in C.</p>
<p>Here is an example of a non-null-terminated string: <code>char greeting[] = {'H', 'e', 'l', 'l', 'o'};</code>This array of characters does not include the null terminator, <code>\0</code>, so it is a non-null-terminated string.</p>
<p>If you try to print a non-null-terminated string using <code>puts()</code>, you will end up getting undefined behavior, such as garbage characters at the end of the string:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
  <span class="hljs-keyword">char</span> greeting[] = {<span class="hljs-string">'H'</span>, <span class="hljs-string">'e'</span>, <span class="hljs-string">'l'</span>, <span class="hljs-string">'l'</span>, <span class="hljs-string">'o'</span>};

  <span class="hljs-built_in">puts</span>(greeting);
}

<span class="hljs-comment">// Ouput when I run the code the first time:</span>
<span class="hljs-comment">// Helloq</span>

<span class="hljs-comment">// Ouput when I run the code a second time:</span>
<span class="hljs-comment">// Hellop</span>

<span class="hljs-comment">// Ouput when I run the code a thrid time:</span>
<span class="hljs-comment">// Hellow</span>
</code></pre>
<h2 id="heading-the-printf-function-vs-the-puts-function-whats-the-difference">The <code>printf()</code> Function VS the <code>puts()</code> Function – What's the Difference?</h2>
<p>You may be wondering what the difference is between <code>printf()</code> and <code>puts()</code>.</p>
<p>The <code>puts()</code> function prints the text as it is, without any formatting. It also automatically adds a newline character at the end of the string.</p>
<p>The <code>printf()</code> function doesn’t automatically add a new line - you have to do it explicitly.</p>
<p>However, it allows for formatted output, and gives you more control and flexibility over where and how you insert different data types into the format string:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
    <span class="hljs-keyword">char</span> name[] = <span class="hljs-string">"John"</span>;
    <span class="hljs-keyword">int</span> age = <span class="hljs-number">30</span>;

    <span class="hljs-comment">// Printing strings using puts()</span>
    <span class="hljs-built_in">puts</span>(<span class="hljs-string">"Using puts():"</span>);
    <span class="hljs-built_in">puts</span>(<span class="hljs-string">"My name is John and I'm 30 years old."</span>);

    <span class="hljs-comment">// Printing strings usingprintf()</span>
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"\nUsing printf():\n"</span>);
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"My name is %s and I'm %d years old. \n"</span>, name, age);
}
</code></pre>
<p>In the example above, the <code>puts()</code> function prints a simple string without any formatting. It also automatically adds a newline character, <code>\n</code>, at the end of the string.</p>
<p>On the other hand, the <code>printf()</code> function formats the string and embeds two variable values. It uses format specifiers, such as <code>%s</code> for strings and <code>%d</code> for integers, to specify the type of data the variables hold, and where the variables should be inserted into the string. It also adds a newline character at the end.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, you learned about the two most commonly used functions in C for printing strings.</p>
<p>The <code>printf()</code> function is commonly used for printing formatted text to the console. It allows you to format your output and print strings, numbers and characters.</p>
<p>The <code>puts()</code> function is more simple compared to <code>printf()</code>. It is great for basic text output and automatically adds a newline character, <code>\n</code>, to the printed string.</p>
<p>Thank you for reading, and happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Def in C – How to Define a Function in C ]]>
                </title>
                <description>
                    <![CDATA[ Functions play a fundamental role in programming in C. They allow you to write code that is organized and easier to maintain. In this article, you'll learn the basics of defining functions in C. What is a Function in C? In programming, a function is ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-define-a-function-in-c/</link>
                <guid isPermaLink="false">661975533d607a40280a2012</guid>
                
                    <category>
                        <![CDATA[ C ]]>
                    </category>
                
                    <category>
                        <![CDATA[ c programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ functions ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Dionysia Lemonaki ]]>
                </dc:creator>
                <pubDate>Fri, 12 Apr 2024 17:54:27 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/npxXWgQ33ZQ/upload/070d054c2dafa7e4a5f90cf0d0af30eb.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Functions play a fundamental role in programming in C. They allow you to write code that is organized and easier to maintain.</p>
<p>In this article, you'll learn the basics of defining functions in C.</p>
<h2 id="heading-what-is-a-function-in-c"><strong>What is a Function in C?</strong></h2>
<p>In programming, a function is a block of code that performs a specific task.</p>
<p>Functions take inputs, process them, perform operations, and produce an output.</p>
<p>Functions are important because they organize your code and promote code reusability.</p>
<p>Instead of writing the same code again and again and repeating yourself, you write code once and then can use it whenever you want to perform that specific task.</p>
<p>In C, there are generally two types of functions:</p>
<ul>
<li><p><strong>Standard library functions</strong>. Standard library functions are provided by the C standard library and defined in header files. Examples of standard library functions include <code>printf()</code> for printing formatted output to the console and <code>scanf()</code> for reading formatted input from the user. Both are defined in the <code>stdio.h</code> header file.</p>
</li>
<li><p><strong>User-defined functions</strong>. User-defined functions are defined by you, the programmer. These functions are tailored to your program’s needs and requirements. For example, a user-defined function may calculate the sum of two numbers or check if a number is even or odd.</p>
</li>
</ul>
<p>In this article, you will learn how to create user-defined functions.</p>
<h2 id="heading-syntax-of-functions-in-c">Syntax of Functions in C</h2>
<p>Here is the general syntax of a function in C:</p>
<pre><code class="lang-c"><span class="hljs-function">return_type <span class="hljs-title">function_name</span><span class="hljs-params">(parameter)</span> </span>{
  <span class="hljs-comment">// function body with the code to be executed</span>
  <span class="hljs-keyword">return</span> value;
}
</code></pre>
<p>Let’s break it down:</p>
<ul>
<li><p>The <code>return_type</code> lets the C compiler know the type of data of the value the function will return after its execution. It can be any valid C data type such as <code>int</code>, <code>float</code>, <code>char</code>, or <code>void</code> if the function doesn’t return a value.</p>
</li>
<li><p>The <code>function_name</code> is the name you give the function. It should be meaningful and accurately describe what the function does. You will later use this to call the function.</p>
</li>
<li><p>The <code>parameter</code> is optional. A parameter is a variable a function accepts as input inside parentheses. A function can receive zero or more parameters. If the function accepts multiple parameters, they are separated by commas. Each parameter consists of the data type followed by a name.</p>
</li>
<li><p>Inside the curly braces, <code>{}</code>, is the function’s body. Here is the actual code, the instructions that perform a specific task.</p>
</li>
<li><p>Inside the function body, there can be an optional return value. You use the <code>return</code> keyword followed by the value you want to return. If the function has a <code>voidreturn_type</code>, you don't need to specify a return value.</p>
</li>
</ul>
<h2 id="heading-how-to-call-a-function-in-c">How to Call a Function in C</h2>
<p>Here is the syntax for calling a function in C:</p>
<pre><code class="lang-c">function_name(arguments);
</code></pre>
<p>Let's break it down:</p>
<ul>
<li><p><code>function_name</code> is the name of the function you want to call. It should be the same name you used to define your function.</p>
</li>
<li><p><code>arguments</code> are the values you pass to the function. If the function accepts any parameters, you pass the arguments in parentheses when you call the function. Each argument is separated by a comma.</p>
</li>
</ul>
<p>If the function returns a value, you can store it in a variable for later use:</p>
<pre><code class="lang-c">data_type result = function_name(arguments);
</code></pre>
<h2 id="heading-how-to-define-and-call-a-function-in-c-example">How to Define and Call a Function in C Example</h2>
<p>Let's look at a simple function that adds two numbers:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">add</span><span class="hljs-params">(<span class="hljs-keyword">int</span> num1, <span class="hljs-keyword">int</span> num2)</span> </span>{
    <span class="hljs-keyword">return</span> num1 + num2;
}

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
    <span class="hljs-keyword">int</span> num1, num2, result;

    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Enter first number: "</span>);
    <span class="hljs-built_in">scanf</span>(<span class="hljs-string">"%d"</span>, &amp;num1);

    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Enter second number: "</span>);
    <span class="hljs-built_in">scanf</span>(<span class="hljs-string">"%d"</span>, &amp;num2);

    result = add(num1, num2);

    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"The sum of %d and %d is %d\n"</span>, num1, num2, result);

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}

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

<span class="hljs-comment">// Enter first number: 2</span>
<span class="hljs-comment">// Enter second number: 3</span>
<span class="hljs-comment">// The sum of 2 and 3 is 5</span>
</code></pre>
<p>Let’s break down the code step by step.</p>
<h3 id="heading-include-the-header-file">Include the Header File</h3>
<p>I first included the library <code>stdio.h</code> with the line <code>#include &lt;stdio.h&gt;</code>.</p>
<p>This line includes the standard input-output library (<code>&lt;stdio.h&gt;</code>), which gives you access to the <code>printf()</code> and <code>scanf()</code> functions. Now, you can receive user input and print text to the console.</p>
<h3 id="heading-define-the-add-function">Define the <code>add</code> Function</h3>
<p>Next, I defined the following function:</p>
<pre><code class="lang-c"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">add</span><span class="hljs-params">(<span class="hljs-keyword">int</span> num1, <span class="hljs-keyword">int</span> num2)</span> </span>{
    <span class="hljs-keyword">return</span> num1 + num2;
}
</code></pre>
<p>This function has an <code>int</code> return type, which indicates that it will return an integer value after execution.</p>
<p>The function is named <code>add</code>, and inside parentheses, it accepts the integer parameters <code>num1</code> and <code>num2</code>.</p>
<p>Within the curly braces, the function body contains the function code. In this case, the function code consists of only the return statement <code>return num1 + num2;</code>. This code calculates the sum of <code>num1</code> and <code>num2</code> using the <code>+</code> operator, and returns the result.</p>
<p>The <code>add()</code> function is defined before being used in the <code>main()</code> function later on. In C, functions must be defined before they are used. By placing the <code>add()</code> function definition above the <code>main()</code> function, the compiler knows about it when it encounters the function call in <code>main()</code>.</p>
<h3 id="heading-define-the-main-function">Define the <code>main()</code> Function</h3>
<p>Next, I defined the <code>main()</code> function, which is the starting point of every C program:</p>
<pre><code class="lang-c"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span> </span>{
    <span class="hljs-keyword">int</span> num1, num2, result;

    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Enter first number: "</span>);
    <span class="hljs-built_in">scanf</span>(<span class="hljs-string">"%d"</span>, &amp;num1);

    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Enter second number: "</span>);
    <span class="hljs-built_in">scanf</span>(<span class="hljs-string">"%d"</span>, &amp;num2);

    result = add(num1, num2);

    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"The sum of %d and %d is %d\n"</span>, num1, num2, result);

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Inside the <code>main()</code> function, I first declared the integer variables <code>num1</code>, <code>num2</code>, and <code>result</code>.</p>
<p>Note that <code>num1</code> and <code>num2</code> variables are different from the <code>num1</code> and <code>num2</code> parameters that the <code>add()</code> function receives. These two variables will store the numbers that the user will enter.</p>
<p>Then, I prompted the user to enter the first number using the <code>printf()</code> function, and used the <code>scanf()</code> function to read the input and store it in the variable <code>num1</code>. The <code>%d</code> format specifier is used to indicate that <code>scanf()</code> should expect an integer input.</p>
<p>I followed the exact same procedure for receiving and storing the second number.</p>
<p>Next, I called the <code>add()</code> function with the <code>num1</code> and <code>num2</code> as arguments. The <code>add()</code> function will add the two numbers together. The result of the calculation is then stored in the <code>result</code> variable.</p>
<p>Following that, I used the <code>printf()</code> function to print the <code>num1</code>, <code>num2</code> and <code>result</code> variables to the console. The format specifier <code>%d</code> is used to print integer values.</p>
<p>Lastly, the line <code>return 0;</code> is a statement that indicates that the program executed successfully. When a C program terminates, it returns an exit status to the operating system, with <code>0</code> typically indicating the program executed without any errors.</p>
<h3 id="heading-execute-the-program">Execute the Program</h3>
<p>When the program is executed, the <code>main()</code> function is called first.</p>
<p>You first see the prompt <code>Enter first number:</code>. In my case, I entered <code>2</code> as the first number.</p>
<p>Once you enter a number, you will see the second prompt: <code>Enter second number:</code>. I entered the number <code>3</code> as the second number.</p>
<p>Then, the <code>add()</code> function is called, which adds the numbers <code>2</code> and <code>3</code>.</p>
<p>Lastly, the line <code>The sum of 2 and 3 is 5</code> is printed to the console.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, you learned the very basics of defining functions in C.</p>
<p>Specifically, you learned about the two different types of functions in C, and the general syntax for defining your own functions.</p>
<p>Lastly, you saw an example of a simple function that added two numbers and returned the result.</p>
<p>Thanks for reading, and happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Learn C# Programming ]]>
                </title>
                <description>
                    <![CDATA[ C# is a popular programming language used for developing a wide array of applications, including web, mobile, desktop, and gaming applications, providing a robust platform for developers to build dynamic and scalable solutions across various industri... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-c-sharp-programming-1/</link>
                <guid isPermaLink="false">66b2040fa8b92c9329236486</guid>
                
                    <category>
                        <![CDATA[ C ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Beau Carnes ]]>
                </dc:creator>
                <pubDate>Mon, 04 Mar 2024 17:52:08 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/03/csharp2.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>C# is a popular programming language used for developing a wide array of applications, including web, mobile, desktop, and gaming applications, providing a robust platform for developers to build dynamic and scalable solutions across various industries.</p>
<p>We just posted a course on the freeCodeCamp.org YouTube channel that will help you master this versatile language. This beginner's course guides you through the basics to advanced C# programming concepts, complete with engaging mini-projects to cement your learning. Aba from CoffeeNCode created this course. </p>
<p>Here is an overview of the different key sections of this course:</p>
<h3 id="heading-introduction-and-environment">Introduction and Environment</h3>
<p>Learn about the course and set up your dev environment by installing Visual Studio 2022, the premier IDE for C# development. Follow step-by-step instructions to set up your environment efficiently.</p>
<h3 id="heading-your-first-steps-in-c">Your First Steps in C</h3>
<p>Embark on your programming adventure by creating your first project and writing the iconic "Hello World" program, laying the foundation for your C# skills.</p>
<h3 id="heading-understanding-data-types-and-operators">Understanding Data Types and Operators</h3>
<p>Explore various data types like numeric, text-based, and Boolean, and learn how to manipulate them using different operators. Understand the significance of the <code>var</code> and <code>const</code> keywords in C#.</p>
<h3 id="heading-practical-exercises">Practical Exercises</h3>
<p>Solidify your understanding through practical exercises, ranging from storing user data to building a simple odd/even number checker.</p>
<h3 id="heading-mastering-inputoutput-and-control-structures">Mastering Input/Output and Control Structures</h3>
<p>Gain proficiency in handling console input/output and making decisions in your code with if and switch statements. Learn to control the flow of your programs with loops and understand the nuances of the conditional operator.</p>
<h3 id="heading-advanced-concepts">Advanced Concepts</h3>
<p>Delve into advanced topics like numeric formatting, the TryParse function, and various string operations. Enhance your programming toolkit with knowledge about arrays, lists, and dictionaries.</p>
<h3 id="heading-functions-and-exception-handling">Functions and Exception Handling</h3>
<p>Discover how to create and utilize functions, handle exceptions gracefully, and employ debugging tools to troubleshoot your code.</p>
<h3 id="heading-object-oriented-programming">Object-Oriented Programming</h3>
<p>Step into the world of object-oriented programming with lessons on structures, classes, and their components. Learn how to define class functions, fields, properties, and more.</p>
<h3 id="heading-capstone-mini-projects">Capstone Mini-Projects</h3>
<p>Apply what you've learned in real-world scenarios through mini-projects, including a times table generator, a Fizz Buzz game, a password checker, and more. These projects are designed to challenge you and enhance your problem-solving skills</p>
<p>C# is a valuable skill that will open numerous doors in your career. Watch the full course on the <a target="_blank" href="https://www.youtube.com/watch?v=YrtFtdTTfv0">freeCodeCamp.org YouTube channel</a> (8-hour watch).</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/YrtFtdTTfv0" 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>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Handle Null References in the Latest Version of C# ]]>
                </title>
                <description>
                    <![CDATA[ By Zoran Horvat C# 12 has just been released, and it continues the long tradition of improvements in the safety of the language's software design and execution.  One of these improvements relates to manipulating null references, a programming concept... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-handle-null-references-in-csharp/</link>
                <guid isPermaLink="false">66d461c47df3a1f32ee7f8c6</guid>
                
                    <category>
                        <![CDATA[ C ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 11 Dec 2023 18:16:55 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/12/article-null.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Zoran Horvat</p>
<p>C# 12 has just been released, and it continues the long tradition of improvements in the safety of the language's software design and execution. </p>
<p>One of these improvements relates to manipulating null references, a programming concept that many developers don't really love. </p>
<p>Using null references in your code can cause all kinds of issues, like exceptions and a lack of information.</p>
<p>This article will teach you how to cope with null references in the latest version of the C# programming language and .NET. The name of the game: let no null pass unattended.</p>
<p>This demonstration will have several stages, each with its own small demo. If you wish to skip through, please use the table of contents below.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><a class="post-section-overview" href="#heading-prerequisites">Prerequisites</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-nullable-reference-types">How to Use Nullable Reference Types</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-the-is-null-and-is-not-null-patterns">How to Use the <code>is null</code> and <code>is not null</code> Patterns</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-type-test-and-set-patterns">How to Use <code>Type-Test-and-Set</code> Patterns</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-property-patterns">How to Use <code>Property</code> Patterns</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-the-null-propagation-and-null-coalescing-operators">How to Use the Null Propagation and Null Coalescing Operators</a></li>
<li><a class="post-section-overview" href="#heading-how-to-work-with-optional-objects">How to Work with Optional Objects</a></li>
<li><a class="post-section-overview" href="#heading-final-notes">Final Notes</a></li>
</ol>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>There are a few prerequisites you will need to meet before proceeding. I assume that you've written enough C# code to see null references in their natural habitat. And I expect you to understand that they can threaten the code's design and stability. </p>
<p>This article will clarify these concepts and identify the issues and solutions using C# syntax and libraries.</p>
<p>If you are ready, we can get started with nullable reference types. That will allow us to set up the working environment and get up to speed for the more complex demos that will follow.</p>
<h2 id="heading-how-to-use-nullable-reference-types">How to Use Nullable Reference Types</h2>
<p>Nullable reference types were introduced in C# 8 and quickly became a mainstay.</p>
<p>The short story is that you can either declare a reference nullable (for example, <code>string? s</code>) or non-nullable (<code>string s</code>). </p>
<p>Note the plot twist: what used to be just a reference before C# 8 (<code>string s</code> was an ordinary reference to a <em>nullable</em> string) has now become something more: a reference that should never be set to null. </p>
<p>That was the breaking change, maybe the first in a decade of C# syntax evolution!</p>
<p>The compiler will do its best to check if all the assignments to a non-nullable reference (the one without the question mark) set it to a proper object. If it finds an execution path that might set it to null, the compiler will issue a compile-time warning. This is called "definite assignment analysis," as the compiler tries to prove that each non-nullable reference is <em>definitely</em> assigned to an object.</p>
<p>If you have already grown accustomed to nullable reference types, I have a question: would you consider not using them today? Probably not.</p>
<p>Let's start with some code. Below, you see two records – one deriving from another. Record types came with C# 9. I am using them here only for brevity. Consider these two types as just the base and the derived class.</p>
<pre><code class="lang-cs"><span class="hljs-keyword">record</span> <span class="hljs-title">Person</span>(<span class="hljs-title">string</span> <span class="hljs-title">FirstName</span>, <span class="hljs-title">string</span> <span class="hljs-title">LastName</span>);

<span class="hljs-keyword">record</span> <span class="hljs-title">Celebrity</span>(<span class="hljs-title">string</span> <span class="hljs-title">FirstName</span>, <span class="hljs-title">string</span> <span class="hljs-title">LastName</span>, <span class="hljs-title">string</span> <span class="hljs-title">KnownFor</span>)
    : <span class="hljs-title">Person</span>(<span class="hljs-title">FirstName</span>, <span class="hljs-title">LastName</span>);
</code></pre>
<p>We can either instantiate a record and assign the instance to a reference, or assign a reference to null.</p>
<p>This is where the definite assignment analysis comes to the table. If there is a sequence of instructions in which the reference ends up being null, we must use the question mark to indicate that the reference can be null.</p>
<pre><code class="lang-cs">Person? left = <span class="hljs-literal">null</span>;
Person? bob = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">"Bob"</span>, <span class="hljs-string">"Coder"</span>);
Person fowler = <span class="hljs-keyword">new</span> Celebrity(<span class="hljs-string">"Martin"</span>, <span class="hljs-string">"Fowler"</span>, <span class="hljs-string">"famous books"</span>);
Person martin = <span class="hljs-keyword">new</span> Celebrity(<span class="hljs-string">"Bob"</span>, <span class="hljs-string">"Martin"</span>, <span class="hljs-string">"SOLID principles"</span>);
</code></pre>
<p>You can see that the second reference (<code>bob</code>) is assigned to a proper object but is still declared nullable. That is perfectly fine in scenarios where an object is coming from the outside, and you might not know whether it will be there or not.</p>
<p>Make sure you don't assign a nullable reference to a non-nullable one, though. That would cause a compile-time warning, which you can raise to the level of compile-time error if you prefer.</p>
<p>It is essential to understand that nullability is not the property of the type but rather a hint given to the compiler. Nullable reference types are only used during the compile-time analysis and are never stored in the compiled type itself.</p>
<p>One consequence is that you cannot declare a nullable type parameter in a generic type. That wouldn't make sense because the compiler has no place to put that information in the compiled type! </p>
<p>But then comes a twist because we are free to indicate any reference of the generic parameter type as nullable, as in the code below. Such a reference is subject to definitive assignment analysis as any other.</p>
<pre><code class="lang-cs"><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">Showcase</span>&lt;<span class="hljs-title">T</span>&gt;(<span class="hljs-params"><span class="hljs-keyword">string</span> caption, Action&lt;T?&gt; action, <span class="hljs-keyword">params</span> T?[] objects</span>)</span>
{
    Console.WriteLine(<span class="hljs-string">$"Showcasing <span class="hljs-subst">{caption}</span>:"</span>.ToUpper());
    <span class="hljs-keyword">foreach</span> (T obj <span class="hljs-keyword">in</span> objects) action(obj);
    Console.WriteLine();
}
</code></pre>
<p>We have defined the utility function to showcase all situations incorporating null references in the rest of this article. As I already pointed out, it would be a compile-time error to declare this generic function as <code>Showcase&lt;T?&gt;</code>, while accepting a nullable <code>T?</code> in the argument list would be perfectly valid. Makes your head spin around!</p>
<p>An even greater mystery is to come: why not remove nullable from the argument list? What would that mean?</p>
<pre><code class="lang-cs"><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">Showcase</span>&lt;<span class="hljs-title">T</span>&gt;(<span class="hljs-params"><span class="hljs-keyword">string</span> caption, Action&lt;T&gt; action, <span class="hljs-keyword">params</span> T[] objects</span>)</span>
{
    Console.WriteLine(<span class="hljs-string">$"Showcasing <span class="hljs-subst">{caption}</span>:"</span>.ToUpper());
    <span class="hljs-keyword">foreach</span> (T obj <span class="hljs-keyword">in</span> objects) action(obj);
    Console.WriteLine();
}
</code></pre>
<p>That would leave it to the caller to determine nullability because – now pay attention! – a concrete generic parameter type <em>can</em> be nullable. It determines the nullability of references, which is a real thing during compilation.</p>
<p>I hope you have started to grasp these concepts more now. Unfortunately, it would take a lot of space to explain this concept in-depth, but I would certainly advise you to learn more about nullability of types. It is now part of C# and is here to stay.</p>
<p>Let me give you a quick demo showcasing the two possible choices:</p>
<pre><code class="lang-cs">Showcase&lt;Person?&gt;(<span class="hljs-string">"Nullable reference types"</span>, Console.WriteLine,
                  left, bob, fowler, martin);
Showcase&lt;Person&gt;(<span class="hljs-string">"Non-nullable reference types"</span>, Console.WriteLine,
                  fowler, martin);
</code></pre>
<p>The first call above allows null references in the arguments, while the second call forces non-nullable references. So the compiler would check the references passed as arguments in that case and raise a warning if any of them is, or could be, null.</p>
<p>That concludes our crash course on nullable reference types in C#. We are ready to proceed with more advanced matters. </p>
<p>Before that, here is the output produced by the code as we have it so far:</p>
<pre><code class="lang-text">SHOWCASING NULLABLE REFERENCE TYPES:
                                                    &lt;-- null is here!
Person { FirstName = Bob, LastName = Coder }
Celebrity { FirstName = Martin, LastName = Fowler, KnownFor = famous books }
Celebrity { FirstName = Bob, LastName = Martin, KnownFor = SOLID principles }

SHOWCASING NON-NULLABLE REFERENCE TYPES:
Celebrity { FirstName = Martin, LastName = Fowler, KnownFor = famous books }
Celebrity { FirstName = Bob, LastName = Martin, KnownFor = SOLID principles }
</code></pre>
<p>Pay attention to the empty line in the output. That is where we have passed null to the <code>Console.WriteLine</code>. The <code>WriteLine</code> method accepts null and treats it the same way it treats an empty string.</p>
<h2 id="heading-how-to-use-the-is-null-and-is-not-null-patterns">How to Use the <code>is null</code> and <code>is not null</code> Patterns</h2>
<p>Once we get nullability right, we can start doing logic around it. The simplest of all operations is asking if a reference is equal to null.</p>
<pre><code class="lang-cs"><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">IsNull</span>(<span class="hljs-params">Person? person</span>)</span>
{
    <span class="hljs-keyword">if</span> (person <span class="hljs-keyword">is</span> <span class="hljs-literal">null</span>)
        Console.WriteLine(<span class="hljs-string">"Sad to see you leaving."</span>);

    <span class="hljs-keyword">if</span> (person <span class="hljs-keyword">is</span> not <span class="hljs-literal">null</span>)
        Console.WriteLine(<span class="hljs-string">$"Everybody say hello to <span class="hljs-subst">{person}</span>"</span>!);
}

Showcase(<span class="hljs-string">"is null and is not null patterns"</span>, IsNull,
         left, bob, fowler, martin);
</code></pre>
<p>The <code>is</code> operator is testing an object against a pattern. We'll meet this operator several more times in the upcoming sections. </p>
<p>In this demo, you can see its simplest use: testing against the <code>null</code> pattern. There are two possibilities there, <code>is null</code> and <code>is not null</code>, with the meaning that appears to require no further explanation. Oh, but that would be a big mistake!</p>
<p>A corner case is covered by <code>is null</code> and <code>is not null</code> patterns, which might be the core reason for introducing these patterns in the first place. Both patterns will avoid calling any overload of the <code>==</code> and <code>!=</code> operators.</p>
<p>So, in theory, a class could overload the <code>==</code> and <code>!=</code> operators and, in doing so, declare that a particular object should be considered equal to a null reference. But the <code>is null</code> pattern will not call the operator overload – thus, it will flatly reject comparing that same non-null object to null.</p>
<p>That is a minor corner case, but it teaches how C# operates under the hood. The bottom line is: you should favor <code>is null</code> over <code>==</code>, and <code>is not null</code> over <code>!=</code> when testing for null/non-null.</p>
<p>Here is the printout produced when we run the function above on a few references, one of them being null.</p>
<pre><code class="lang-text">SHOWCASING IS NULL AND IS NOT NULL PATTERNS:
Sad to see you leaving.
Everybody say hello to Person { FirstName = Bob, LastName = Coder }
Everybody say hello to Celebrity { FirstName = Martin, LastName = Fowler, KnownFor = famous books }
Everybody say hello to Celebrity { FirstName = Bob, LastName = Martin, KnownFor = SOLID principles }
</code></pre>
<h2 id="heading-how-to-use-type-test-and-set-patterns">How to Use <code>Type-Test-and-Set</code> Patterns</h2>
<p>The time has come to raise the bar and use some of the more complex methods of processing nullable references. We will remain with the <code>is</code> operator, but this time, we'll use its more potent form: testing type patterns.</p>
<p>Each reference in C# resolves into an object (or a lack of – a null), and each object we reference possesses the type descriptor. That is at the core of any object-oriented language. </p>
<p>So it's pretty easy for the .NET runtime to check whether a reference is pointing to an object – and, if so, whether that object's runtime type derives from a specific type, directly or indirectly.</p>
<p>That was a mouthful, wasn't it? Let's split that up into bits:</p>
<ul>
<li>To test whether a reference references an actual object, that is the <code>person is not null</code> pattern.</li>
<li>To add the test whether that object is assignable to a particular type, we use the type pattern instead: <code>person is Celebrity</code>.</li>
<li>Finally, to capture the reference to the desired type and use it in subsequent statements and expressions, we use the full-blown type-test-and-set expression: <code>person is Celebrity celeb</code>.</li>
</ul>
<p>These are the three stages of extracting information from a reference, each more potent than the other. </p>
<p>Without further ado, here is the method that exercises the most detailed form: testing against null and downcasting, all packed in one condensed expression:</p>
<pre><code class="lang-cs"><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">TypeTestAndSet</span>(<span class="hljs-params">Person? person</span>)</span>
{
    <span class="hljs-keyword">string</span> report = person <span class="hljs-keyword">switch</span>
    {
        Celebrity celebrity =&gt;
            <span class="hljs-string">$"<span class="hljs-subst">{celebrity.FirstName}</span> <span class="hljs-subst">{celebrity.LastName}</span> known for <span class="hljs-subst">{celebrity.KnownFor}</span>"</span>,
        Person commonPerson =&gt;
            <span class="hljs-string">$"<span class="hljs-subst">{commonPerson.FirstName}</span> <span class="hljs-subst">{commonPerson.LastName}</span>"</span>,
        _ =&gt; <span class="hljs-keyword">string</span>.Empty,
    };
    <span class="hljs-keyword">if</span> (!<span class="hljs-keyword">string</span>.IsNullOrEmpty(report)) Console.WriteLine(report);

    <span class="hljs-keyword">if</span> (person <span class="hljs-keyword">is</span> Celebrity celeb) Console.WriteLine(<span class="hljs-string">"*** Did you see a celebrity?"</span>);
}

Showcase(<span class="hljs-string">"Type test and set patterns"</span>, TypeTestAndSet,
         left, bob, fowler, martin);
</code></pre>
<p>You may have noticed that these expressions are effectively implementing safe downcasting. Downcasting was frowned upon for decades, accused (mostly rightfully) of causing code defects and design flaws. </p>
<p>But times they are a-changin'! Type test and set expressions are coming to software development from functional programming. </p>
<p>This article is not a place to discuss the differences between type testing and downcasting as we knew it in object-oriented languages of the past. I strongly encourage you to learn more about this intriguing topic before judging.</p>
<pre><code class="lang-text">SHOWCASING TYPE TEST AND SET PATTERNS:
Bob Coder
Martin Fowler known for famous books
*** Did you see a celebrity?
Bob Martin known for SOLID principles
*** Did you see a celebrity?
</code></pre>
<p>Here, you can see the output produced by the function above. As you can see, each actual type is captured correctly, creating its specific output. And the dreaded null was left out – I have indeed passed a null reference to the function at one instant but hadn't matched any of the patterns, and so was ignored.</p>
<p>This demo would be incomplete without one crucial note. The <code>switch</code> expression (of C# 8) is expecting patterns in order from more specific to more general ones. It would be an error to list a more specific pattern after a more general one. The general pattern would overshadow the subsequent one, never letting its right hand execute. Therefore, the <code>switch</code> expression like the one below causes a compile-time error in C#.</p>
<pre><code class="lang-cs">person <span class="hljs-keyword">switch</span>
{
    Person commonPerson =&gt;
        <span class="hljs-string">$"<span class="hljs-subst">{commonPerson.FirstName}</span> <span class="hljs-subst">{commonPerson.LastName}</span>"</span>,
    Celebrity celebrity =&gt;              <span class="hljs-comment">// &lt;-- error</span>
        <span class="hljs-string">$"<span class="hljs-subst">{celebrity.FirstName}</span> <span class="hljs-subst">{celebrity.LastName}</span> known for <span class="hljs-subst">{celebrity.KnownFor}</span>"</span>,
    _ =&gt; <span class="hljs-keyword">string</span>.Empty,
};
</code></pre>
<h2 id="heading-how-to-use-property-patterns">How to Use <code>Property</code> Patterns</h2>
<p>An exciting development follows if you push pattern matching even further. One specific form is the properties pattern – one aimed to match the values and attributes of properties of an object (if the object exists!).</p>
<pre><code class="lang-cs"><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">PropertyPatterns</span>(<span class="hljs-params">Person? person</span>)</span>
{
    <span class="hljs-keyword">if</span> (person <span class="hljs-keyword">is</span> { FirstName: <span class="hljs-string">"Bob"</span>})
        Console.WriteLine(<span class="hljs-string">$"Greet Bob, the one and only <span class="hljs-subst">{person.FirstName}</span> <span class="hljs-subst">{person.LastName}</span>!"</span>);
    <span class="hljs-keyword">else</span>
        Console.WriteLine(<span class="hljs-string">"Not a Bob"</span>);
}

Showcase(<span class="hljs-string">"Property patterns"</span>, PropertyPatterns,
         left, bob, fowler, martin);
</code></pre>
<p>You don't have to specify the type if you are not interested in downcasting. It will be the type of the reference to the left of the <code>is</code> operator. </p>
<p>But using the <code>is</code> operator implies a null test. Any reference passing the <code>is</code> test will be non-null and safe to check its property values on the right-hand side of the expression.</p>
<p>Therefore, we read this <code>if</code> instruction's condition as follows: If <code>person</code> is not null, and its property <code>FirstName</code> has a value Bob, then...</p>
<p>Here is the output produced when we call the function above:</p>
<pre><code class="lang-text">SHOWCASING PROPERTY PATTERNS:
Not a Bob
Greet Bob, the one and only Bob Coder!
Not a Bob
Greet Bob, the one and only Bob Martin!
</code></pre>
<h2 id="heading-how-to-use-the-null-propagation-and-null-coalescing-operators">How to Use the Null Propagation and Null Coalescing Operators</h2>
<p>So far, we have been doing things to objects, which is awkward in an object-oriented design. Remember, in object-oriented programming, it is the object that exposes behavior, and, as the object's users, we only make calls to its methods.</p>
<p>The problems still come when the reference we expect to point to an object is nullable. Making an unguarded call on the null reference was the primary source of defects. But now, with nullable references and definite assignment checks done for us, we should be safe from the dreaded <code>NullReferenceExceptions</code>.</p>
<p>Consider having a method exposed by the class. We can use <code>ToString</code> as a simple example.</p>
<pre><code class="lang-cs"><span class="hljs-keyword">record</span> <span class="hljs-title">Person</span>(<span class="hljs-title">string</span> <span class="hljs-title">FirstName</span>, <span class="hljs-title">string</span> <span class="hljs-title">LastName</span>)
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">string</span> <span class="hljs-title">ToString</span>(<span class="hljs-params"></span>)</span> =&gt;
        <span class="hljs-string">$"<span class="hljs-subst">{FirstName}</span> <span class="hljs-subst">{LastName}</span>"</span>;
}

<span class="hljs-keyword">record</span> <span class="hljs-title">Celebrity</span>(<span class="hljs-title">string</span> <span class="hljs-title">FirstName</span>, <span class="hljs-title">string</span> <span class="hljs-title">LastName</span>, <span class="hljs-title">string</span> <span class="hljs-title">KnownFor</span>)
    : <span class="hljs-title">Person</span>(<span class="hljs-title">FirstName</span>, <span class="hljs-title">LastName</span>)
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">string</span> <span class="hljs-title">ToString</span>(<span class="hljs-params"></span>)</span> =&gt;
        <span class="hljs-string">$"<span class="hljs-subst">{<span class="hljs-keyword">base</span>.ToString()}</span> known for <span class="hljs-subst">{KnownFor}</span>"</span>;
}
</code></pre>
<p>There is a substantial difference between calling <code>ToString</code> on <code>Person</code> and on <code>Person?</code> types. The latter one is nullable, and therefore an unguarded call might cause dereferencing a null reference, leading to a dreaded <code>NullReferenceException</code>, as you can imagine.</p>
<pre><code class="lang-cs">Person a = ...;
Person? b = ...;

<span class="hljs-keyword">string</span> x = a.ToString();      <span class="hljs-comment">// safe</span>
<span class="hljs-keyword">string</span> y = b.ToString();      <span class="hljs-comment">// unsafe</span>
</code></pre>
<p>Enter the null-propagation operator (<code>?.</code>)! We can safely make an optional call to a method, provided the reference is non-null.</p>
<pre><code class="lang-cs">Person a = ...;
Person? b = ...;

<span class="hljs-keyword">string</span> x = a.ToString();      <span class="hljs-comment">// safe</span>
<span class="hljs-keyword">string</span>? y = b?.ToString();    <span class="hljs-comment">// safe</span>
</code></pre>
<p>But observe the consequences. If the method returns <code>void</code>, the call will be ignored on a null reference. If the method returns a type, then the result will be the nullable version of that type. You cannot expect a string from <code>ToString</code> on a nullable reference, you see? The compiler can only promise a nullable string instead.</p>
<p>And what if we really wanted a string, a true one? Enter the null-coalescing operator (<code>??</code>)! We can easily convert a nullable reference to a non-nullable one by supplying a default to take when the actual value is null at run time.</p>
<pre><code class="lang-cs"><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">NullPropagationAndCoalescing</span>(<span class="hljs-params">Person? person</span>)</span>
{
    <span class="hljs-keyword">string</span> report = person?.ToString() ?? <span class="hljs-keyword">string</span>.Empty;
    <span class="hljs-keyword">if</span> (!<span class="hljs-keyword">string</span>.IsNullOrEmpty(report)) Console.WriteLine(report);
}

Showcase(<span class="hljs-string">"Null propagation and null coalescing operators"</span>,
         NullPropagationAndCoalescing,
         left, bob, fowler, martin);
</code></pre>
<p>In this example, we make an optional call to the <code>ToString</code> method first but then short-circuit the result to an empty string if the reference were null. The result is that any null reference would produce an empty string for printout.</p>
<pre><code class="lang-text">SHOWCASING NULL PROPAGATION AND NULL COALESCING OPERATORS:
                            &lt;-- An empty string printed here
Bob Coder
Martin Fowler known for famous books
Bob Martin known for SOLID principles
</code></pre>
<h2 id="heading-how-to-work-with-optional-objects">How to Work With Optional Objects</h2>
<p>The last method of addressing nulls in this article will actually not use nulls. Another riddle! The idea is to avoid nulls altogether by modeling the objects as possibly missing. Mind the word "possibly" – that will become part of the type declaration the same way nullability was.</p>
<p>If you are new to optional objects, then this short explanation will be anything but sufficient to learn about them. C# has no native support for optional objects. You can choose one of the many implementations available on NuGet, the most popular one being the LanguageExt library.</p>
<pre><code class="lang-text">dotnet add package LanguageExt.Core
</code></pre>
<p>An optional object of some type is an object that either exists or does not exist. Whichever the case, the optional object itself will always exist. Another riddle for you to solve! </p>
<p>Here is how we would declare a few optional objects:</p>
<pre><code class="lang-cs"><span class="hljs-keyword">using</span> LanguageExt;

Option&lt;Person&gt;[] maybePeople = 
{
    Option&lt;Person&gt;.None,
    Option&lt;Person&gt;.Some(bob),
    Option&lt;Person&gt;.Some(fowler),
    Option&lt;Person&gt;.Some(martin),
};
</code></pre>
<p>The two shapes of an optional object are usually referred to as <code>None</code> and <code>Some</code>. The <code>Some</code> variant must contain an actual object. That completes the creation of optional objects and the code that will never have a null reference.</p>
<p>But what is the difference compared to nullable references? Why should we use optional objects at all?</p>
<p>The short story is that optional objects let us apply functions to the optional object's content – if present. The optional object will either invoke the function and pass the content to it or skip calling it altogether if there is no content.</p>
<p>Therefore, an optional type is a single place where that calling protocol is now implemented, the protocol in many ways equivalent to safely dereferencing nullable references.</p>
<pre><code class="lang-cs"><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">Optional</span>(<span class="hljs-params">Option&lt;Person&gt; maybePerson</span>)</span>
{
    <span class="hljs-keyword">string</span> report = maybePerson.Match(
        person =&gt; person.ToString(),
        <span class="hljs-keyword">string</span>.Empty);
    maybePerson.Do(Console.WriteLine);
}

Showcase(<span class="hljs-string">"Optional objects"</span>, Optional, maybePeople);
</code></pre>
<p>The <code>Match</code> method covers both possibilities: It either maps the <code>Person</code> object to a string or substitutes an empty string if the person is missing. The <code>Do</code> method will only pass content to the console if content exists.</p>
<p>Here is the printout produced by the <code>Do</code> method:</p>
<pre><code class="lang-text">SHOWCASING OPTIONAL OBJECTS:
Bob Coder
Martin Fowler known for famous books
Bob Martin known for SOLID principles
</code></pre>
<p>You will only see the <code>Some</code> variants printed out. The only missing object in the input array has produced no output because that optional instance has ignored the action passed to its <code>Do</code> method.</p>
<p>The most significant benefit of using optional objects over nullable references is their ability to apply other functions. We might already have many different classes and methods implemented in our codebase, all methods working on non-nullable references. Optional objects can bridge the gap between potentially missing objects and the common methods that are only operational when nothing is missing.</p>
<h2 id="heading-final-notes">Final Notes</h2>
<p>In this tutorial, we started by declaring nullable objects and testing their existence using the <code>is</code> operator.</p>
<p>Then, we extended the example by displaying the richness of pattern-matching expressions: type test and set and property pattern expressions.</p>
<p>We then moved the focus from consuming objects to calling their behavior from the null-propagation operator over the null-coalescing operator, landing in the vast field of functional programming and optional objects.</p>
<p>I hope you enjoyed the ride. In place of farewell, I will invite you to learn more about optional objects in C# by watching my recent video <a target="_blank" href="https://youtu.be/8-2xr_kBRnQ">How to Avoid Null Reference Exceptions: Optional Objects in C#</a>.[</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Earn a Free C# Certification from Microsoft and freeCodeCamp ]]>
                </title>
                <description>
                    <![CDATA[ I'm excited to announce that Microsoft and freeCodeCamp have teamed up to bring you a new free professional certification: the Foundational C# Certification. This professional certification includes 35 hours of training from Microsoft and an online c... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/free-microsoft-c-sharp-certification/</link>
                <guid isPermaLink="false">66b8d32cf8e5d39507c4c0e5</guid>
                
                    <category>
                        <![CDATA[ C ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Career ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Certification ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Quincy Larson ]]>
                </dc:creator>
                <pubDate>Mon, 28 Aug 2023 12:53:25 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/08/Microsoft-C-Sharp-Certification-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>I'm excited to announce that Microsoft and freeCodeCamp have teamed up to bring you a new free professional certification: the Foundational C# Certification.</p>
<p>This professional certification includes 35 hours of training from Microsoft and an online certification exam by freeCodeCamp.</p>
<p>By the end of this process, you'll have earned your very own verified certification that you can add to your Résumé, LinkedIn, or CV.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/Microsoft-Certification-with-Sample-Watermark.png" alt="Image" width="600" height="400" loading="lazy">
<em>A sample Foundational C# certification.</em></p>
<p>Without further ado, here are the skills this new free professional certification will teach you:</p>
<ol>
<li>Creating your first C# app</li>
<li>Coding simple C# apps</li>
<li>Creating methods in your C# apps</li>
<li>Adding logic to your C# apps</li>
<li>Working with variable data in your C# apps</li>
<li>Debugging C# apps</li>
</ol>
<p>Then you'll sign freeCodeCamp's Academic Honesty pledge and take our 1-hour 80-question certification exam. If you receive a passing score, you'll earn your certification.</p>
<h2 id="heading-how-to-earn-the-foundational-c-certification">How to Earn the Foundational C# Certification</h2>
<p>Here are the steps for earning this certification, which will take an estimated 35 hours of studying, plus 1 to 2 hours to pass the exam.</p>
<ol>
<li>Go to the <a target="_blank" href="https://www.freecodecamp.org/learn/foundational-c-sharp-with-microsoft/">Foundational C# Certification path on freeCodeCamp</a>. Here you'll find the training content under "Courses". Press "Expand course" to find all the modules within each course. Each module in the path correlates to a piece of C# training content on Microsoft Learn.</li>
<li>Click on each module in the course to find the link to the training content for that module.</li>
<li>Complete the training content on Microsoft Learn. (Note: If you have previously completed the training content, you do not need to redo it.)</li>
<li>Once you are done with each section, complete the comprehension check question on freeCodeCamp.</li>
<li>At the end of each course, you'll receive a Trophy on Microsoft Learn. Enter the Trophy link in the Trophy page on freeCodeCamp. Each step on freeCodeCamp will also show instructions for how you can claim and submit these Trophies.</li>
</ol>
<h2 id="heading-learn-together-with-the-microsoft-team">Learn together with the Microsoft Team</h2>
<p>In addition to providing the C# training content on Microsoft Learn, the .NET team is hosting six office-hour style streaming events to help you succeed. </p>
<p>These streams will be every Wednesday at 2:00 pm UTC from September 20 to October 25.</p>
<p>During each of these session, expert presenters will review a training course, walk you through a guided project, and answer your questions. </p>
<p>You can also stay updated with live and on-demand sessions via the <a target="_blank" href="https://www.youtube.com/dotnet">.NET YouTube channel</a>.</p>
<p>We've also published a video walkthrough for the C# certification on the freeCodeCamp YouTube channel, taught by freeCodeCamp instructor and veteran C# developer Gavin Lon.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/6GQAE7iLOhY" 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 you can ask questions and get support on <a target="_blank" href="https://forum.freecodecamp.org/c/c-sharp/588">the C# section of the freeCodeCamp Forum</a>.</p>
<h2 id="heading-this-is-a-dream-come-true-for-the-freecodecamp-community">This is a Dream Come True for the freeCodeCamp Community</h2>
<p>We've long encouraged campers to obtain professional certifications from tech companies – even though many of these certifications require a credit card and an exam fee.</p>
<p>By making this certification freely available to everyone, we can ensure that anyone – anywhere – can earn a high quality professional certification, regardless of their ability to pay.</p>
<p>I want to thank Microsoft who created a grant to make development of this certification possible. And I want to thank the many developers on both Microsoft's .NET team and freeCodeCamp's instructional design team that made this a reality.</p>
<p><a target="_blank" href="https://www.freecodecamp.org/learn/foundational-c-sharp-with-microsoft/">Let's go get certified, shall we?</a> Happy coding. 🏕️</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Action and Func Delegates in C# – Explained with Examples ]]>
                </title>
                <description>
                    <![CDATA[ By Umoh Tobby In C#, types called delegates represent references to methods with specific signatures.  Developers use delegates to implement callback methods, handle events, and perform tasks where executing a method at a later time is necessary.  C#... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/action-and-func-delegates-in-c-sharp/</link>
                <guid isPermaLink="false">66d4614937bd2215d1e245e9</guid>
                
                    <category>
                        <![CDATA[ C ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 06 Jul 2023 19:46:15 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/07/Untitled--Copy---1-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Umoh Tobby</p>
<p>In C#, types called delegates represent references to methods with specific signatures. </p>
<p>Developers use delegates to implement callback methods, handle events, and perform tasks where executing a method at a later time is necessary. </p>
<p>C# offers various delegates, and two commonly used ones are Action and Func, both defined in the System namespace.</p>
<p>In this tutorial, you'll learn about the Action and Func delegates in C#.</p>
<p>To download the source code for this article, visit this <strong><a target="_blank" href="https://github.com/TobbyJay/ActionAndFuncDelegate">GitHub Repository</a></strong>.</p>
<p>Let’s begin by discussing the Action delegate and exploring its usage</p>
<h2 id="heading-what-is-the-action-delegate-in-c">What is the Action Delegate in C#?</h2>
<p>The Action delegate is a predefined delegate type that encapsulates a method with zero or more input parameters that doesn't return a value. In other words, an Action delegate represents a void-returning method.</p>
<p>Consider this example, demonstrating the usage of an Action delegate in a simple console calculator application:</p>
<pre><code class="lang-c#">Action&lt;<span class="hljs-keyword">int</span>, <span class="hljs-keyword">int</span>&gt; ActionCalculator = (a, b) =&gt;
{
    Console.WriteLine(<span class="hljs-string">$"Addition result: <span class="hljs-subst">{a + b}</span>"</span>);
    Console.WriteLine(<span class="hljs-string">$"Subtraction result: <span class="hljs-subst">{a - b}</span>"</span>);
    Console.WriteLine(<span class="hljs-string">$"Multiplication result: <span class="hljs-subst">{a * b}</span>"</span>);
    Console.WriteLine(<span class="hljs-string">$"Division result: <span class="hljs-subst">{a / b}</span>"</span>);
};

ActionCalculator(<span class="hljs-number">4</span>, <span class="hljs-number">2</span>);
</code></pre>
<p>In this example, we defined an Action delegate named ActionCalculator. It takes two integer parameters and performs four basic arithmetic operations using those parameters. Then, we invoke the delegate with the values 4 and 2.</p>
<p>The application produced the following output upon running:</p>
<pre><code class="lang-c#">Addition result: <span class="hljs-number">6</span>
Subtraction result: <span class="hljs-number">2</span>
Multiplication result: <span class="hljs-number">8</span>
Division result: <span class="hljs-number">2</span>
</code></pre>
<p>As you can see, utilizing an Action delegate simplifies the process of passing a method as a parameter to another method.</p>
<h2 id="heading-what-is-the-func-delegate-in-c">What is the Func Delegate in C#?</h2>
<p>The Func delegate is another predefined delegate type that represents a method with zero or more input parameters that returns a value. Unlike the Action delegate, the return type of a Func delegate can be any type.</p>
<p>Let’s consider an example of using a Func delegate in a simple console calculator application.</p>
<p>In this example, we define a Calculator class:</p>
<pre><code class="lang-c#"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Calculator</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">Add</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> a, <span class="hljs-keyword">int</span> b</span>)</span> =&gt; a + b;
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">Subtract</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> a, <span class="hljs-keyword">int</span> b</span>)</span> =&gt; a - b;
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">Multiply</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> a, <span class="hljs-keyword">int</span> b</span>)</span> =&gt; a * b;
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">Divide</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> a, <span class="hljs-keyword">int</span> b</span>)</span> =&gt; a / b;
}
</code></pre>
<p>The Calculator class contains methods to perform four basic arithmetic operations.</p>
<p>Next, we create four Func delegates, with each delegate pointing to one of the calculator’s methods:</p>
<pre><code class="lang-c#"><span class="hljs-keyword">var</span> FuncCalculator = <span class="hljs-keyword">new</span> Calculator();

Func&lt;<span class="hljs-keyword">int</span>, <span class="hljs-keyword">int</span>, <span class="hljs-keyword">int</span>&gt; <span class="hljs-keyword">add</span> = FuncCalculator.Add;
Func&lt;<span class="hljs-keyword">int</span>, <span class="hljs-keyword">int</span>, <span class="hljs-keyword">int</span>&gt; subtract = FuncCalculator.Subtract;
Func&lt;<span class="hljs-keyword">int</span>, <span class="hljs-keyword">int</span>, <span class="hljs-keyword">int</span>&gt; multiply = FuncCalculator.Multiply;
Func&lt;<span class="hljs-keyword">int</span>, <span class="hljs-keyword">int</span>, <span class="hljs-keyword">int</span>&gt; divide = FuncCalculator.Divide;

Console.WriteLine(<span class="hljs-string">$"Addition result: <span class="hljs-subst">{<span class="hljs-keyword">add</span>(<span class="hljs-number">4</span>, <span class="hljs-number">2</span>)}</span>"</span>);
Console.WriteLine(<span class="hljs-string">$"Subtraction result: <span class="hljs-subst">{subtract(<span class="hljs-number">4</span>, <span class="hljs-number">2</span>)}</span>"</span>);
Console.WriteLine(<span class="hljs-string">$"Multiplication result: <span class="hljs-subst">{multiply(<span class="hljs-number">4</span>, <span class="hljs-number">2</span>)}</span>"</span>);
Console.WriteLine(<span class="hljs-string">$"Division result: <span class="hljs-subst">{divide(<span class="hljs-number">4</span>, <span class="hljs-number">2</span>)}</span>"</span>);
</code></pre>
<p>Finally, we invoke each of the delegates with the values 4 and 2 and print the results to the console.</p>
<p>The calculator application displayed the following output upon running:</p>
<pre><code class="lang-c#">Addition result: <span class="hljs-number">6</span>
Subtraction result: <span class="hljs-number">2</span>
Multiplication result: <span class="hljs-number">8</span>
Division result: <span class="hljs-number">2</span>
</code></pre>
<p>Func delegates offer a straightforward approach to defining and utilising methods by passing them as parameters and returning them as results.</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>In conclusion, Action and Func delegates provide a way to encapsulate a method call within a delegate object. </p>
<p>Developers use Action delegates when a method does not return a value, and Func delegates when a method returns a value.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Learn Advanced C# Concepts ]]>
                </title>
                <description>
                    <![CDATA[ As a software developer, staying up-to-date with evolving technologies is a cornerstone of your career.  C# is a powerful language that has continued to evolve and transform the landscape of software development. If you are a programmer with some exp... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-advanced-c-concepts/</link>
                <guid isPermaLink="false">66b203e082069b4c678c98eb</guid>
                
                    <category>
                        <![CDATA[ C ]]>
                    </category>
                
                    <category>
                        <![CDATA[ youtube ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Beau Carnes ]]>
                </dc:creator>
                <pubDate>Tue, 27 Jun 2023 13:51:52 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/06/csharp.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>As a software developer, staying up-to-date with evolving technologies is a cornerstone of your career. </p>
<p>C# is a powerful language that has continued to evolve and transform the landscape of software development. If you are a programmer with some experience in C# and looking to deepen your knowledge, then you’ve come to the right place.</p>
<p>We just published an advanced C# course on the freeCodeCamp.org YouTube channel. The course was developed by Gavin Lon. Gavin is an experienced developer and freeCodeCamp team member.</p>
<p>The course curriculum is structured to ensure a seamless learning experience, as it covers an array of sophisticated C# topics that are essential for the modern developer.</p>
<h2 id="heading-course-overview">Course Overview</h2>
<ol>
<li><strong>Introduction and Course Overview</strong>: The course starts with an introduction and an overview to set the stage for the exciting learning journey ahead.</li>
<li><strong>In-Depth Study of Delegates</strong>: The delegates section is an extensive exploration that lays the foundation for understanding the role and importance of delegates in C#. You will be exposed to practical examples, learn about the different types of delegates, and understand how asynchronous programming is realized through delegates.</li>
<li><strong>Mastering Events in C#</strong>: Following delegates, the course tackles events in C#. This sections starts with an introduction to the intricacies of events and concludes by teaching how events integrate into design patterns like the Observer Pattern.</li>
<li><strong>Unraveling Generics</strong>: Generics are powerful features in C# that are essential for type-safe code. This section takes you through the basic concepts, constraints in generics, and how delegates and events can be used with generics. It also covers how generics play a crucial role in design patterns.</li>
<li><strong>Asynchronous Programming with Async/Await</strong>: Here, the course delves into asynchronous programming which is fundamental for writing efficient and responsive applications. You'll learn the best practices, how to manage tasks, and handle cancellations effectively.</li>
<li><strong>Demystifying LINQ</strong>: The Language Integrated Query (LINQ) section gives you insights into querying data effectively. This part covers the different operators available, how to create queries, and efficiently utilize LINQ for data manipulation.</li>
<li><strong>Attributes and Reflection in C#</strong>: Gavin explores how to use attributes in C# and how reflection allows you to inspect and interact with object metadata at runtime.</li>
<li><strong>Journey through .NET</strong>: The course concludes with a focus on the evolution of the .NET framework, from .NET Core to the newer versions of .NET, giving you insights into the direction and future of C# and .NET technology.</li>
</ol>
<p>With hands-on examples and best practices, this course will pay dividends in your journey as a C# developer. Watch the full course on the <a target="_blank" href="https://youtu.be/YT8s-90oDC0">freeCodeCamp.org YouTube channel</a> (15-hour watch).</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/YT8s-90oDC0" 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>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
