<?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>Sat, 23 May 2026 16:27:32 +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[ 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>
        
            <item>
                <title>
                    <![CDATA[ Strings in C# – What's New, Explained with Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ By Deborah Kurata Much of what we work with in our code are strings. Let's look at some of the newish things about C# strings ... including raw string literals and raw string interpolation that are new in C# 11. Raw string literals make it easy to bu... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/new-ish-things-about-c-strings/</link>
                <guid isPermaLink="false">66d45e0ed1ffc3d3eb89ddc7</guid>
                
                    <category>
                        <![CDATA[ C ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 26 May 2023 13:49:06 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/05/things-about-strings.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Deborah Kurata</p>
<p>Much of what we work with in our code are strings. Let's look at some of the newish things about C# strings ... including raw string literals and raw string interpolation that are new in C# 11.</p>
<p>Raw string literals make it easy to build complex, multi-line strings, including JSON, in a simple and flexible way. And with no escaping necessary.</p>
<p>Watch the associated video here:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/A5FRgglBkJ8" 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>Find the <a target="_blank" href="https://github.com/DeborahK/CSharp-Examples">sample code here</a>. </p>
<p>In this article, we'll start with some of the current techniques we use to handle strings, problems we've faced using those techniques, and new C# 11 features that help with our string handling.</p>
<h2 id="heading-quoted-string-literal"><strong>Quoted String Literal</strong></h2>
<p>The primary way we've worked with strings in C# is using a quoted string literal. These have been available since the beginning of C#.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">string</span> header = <span class="hljs-string">"&lt;div class=\"card-header\"&gt;Vehicle Detail&lt;/div&gt;"</span>
</code></pre>
<p>But if we have quotes in our string, the string gets a bit messy. We escape those quotes with a backslash. That way the C# compiler can tell the difference between the outside quotes and any quotes within the string.</p>
<p>Standard quoted string literals are often best for single line strings with no characters that need to be escaped.</p>
<h2 id="heading-verbatim-string-literal"><strong>Verbatim String Literal</strong></h2>
<p>For strings that span across multiple lines, we use a verbatim string literal. We define a verbatim string literal with an at sign in front of the first quotation mark. Verbatim means "as is", and is meant to define a multi-line string that displays "as is".</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">string</span> header = <span class="hljs-string">@"
   &lt;div class=""card""&gt;
     &lt;div class=""card-header""&gt;
       Vehicle Detail
   &lt;/div&gt;
"</span>;
</code></pre>
<p>But once again, quotation marks are a challenge! Verbatim string literals require that we use double quotation marks to indicate a quotation mark within a string. This doesn't look horrible in this case ... but when creating a string with lots of quotation marks, like defining JSON, it can be quite messy.</p>
<p>Plus, indentation of verbatim string literals can be a problem.</p>
<pre><code class="lang-csharp">  <span class="hljs-keyword">foreach</span> (<span class="hljs-keyword">var</span> vehicle <span class="hljs-keyword">in</span> vehicles)
  {
    <span class="hljs-keyword">if</span> (goodCredit)
    {
      <span class="hljs-keyword">if</span> (newVehicle)
      {
        message = <span class="hljs-string">@"
          Congratulations on your new vehicle!
          We hope you enjoy driving it as much as we enjoyed building it.
          "</span>;
      }
     }
   }
</code></pre>
<p>Above we have a typical bit of code with multiple indentations. And we indent the message nicely within the if block. But then if we display the message, the indentations are included as shown in Figure 1. That may not be the desired result.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/verbatim-string.png" alt="Image" width="600" height="400" loading="lazy">
<em>Figure 1. Verbatim string literal retains its indentation</em></p>
<p>To fix it, we'd have to unindent the text to line up with the left margin.</p>
<pre><code class="lang-csharp">  <span class="hljs-keyword">foreach</span> (<span class="hljs-keyword">var</span> vehicle <span class="hljs-keyword">in</span> vehicles)
  {
    <span class="hljs-keyword">if</span> (goodCredit)
    {
      <span class="hljs-keyword">if</span> (newVehicle)
      {
        message = <span class="hljs-string">@"
Congratulations on your new vehicle!
We hope you enjoy driving it as much as we enjoyed building it.
"</span>;
      }
    }
   }
</code></pre>
<p>The result is then better as shown in Figure 2. But the code looks a bit messy. And if some unsuspecting developer comes along to "clean up" the indentation, our result is not as we intended.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/indentation-not-saved.png" alt="Image" width="600" height="400" loading="lazy">
<em>Figure 2. Verbatim string literal must be outdented in the code to appear with no indentation</em></p>
<h2 id="heading-raw-string-literal-new-in-c11"><strong>Raw String Literal (new in C#11)</strong></h2>
<p>A new feature in C# 11, released in 2022, is a <strong>raw string literal</strong>. A raw string literal is a new format for string literals. They allow for whitespace, new lines, embedded quotes, other special characters, or whatever!</p>
<p>A raw string literal begins with at least 3 quotes. And ends with a matching set of quotes. Everything on the lines between the opening and closing quotes is the desired string.</p>
<pre><code class="lang-csharp"> <span class="hljs-keyword">string</span> header = <span class="hljs-string">""</span><span class="hljs-string">"
      &lt;div class="</span>card<span class="hljs-string">"&gt;
        &lt;div class="</span>card-header<span class="hljs-string">"&gt;
          Vehicle Detail
        &lt;/div&gt;
      &lt;/div&gt;
    "</span><span class="hljs-string">""</span>;
</code></pre>
<p>Notice that there is no need for doubling of the quotes or any escape characters. The string displays exactly as it is. This is a much better choice for multi-line strings over the original verbatim string literal.</p>
<p>Another important feature of raw string literals is that the resulting string aligns to the closing quotes. In the example below, we align the message with the beginning of the closing quote.</p>
<pre><code class="lang-csharp">  <span class="hljs-keyword">foreach</span> (<span class="hljs-keyword">var</span> vehicle <span class="hljs-keyword">in</span> vehicles)
  {
    <span class="hljs-keyword">if</span> (goodCredit)
    {
      <span class="hljs-keyword">if</span> (newVehicle)
      {
        message = <span class="hljs-string">""</span><span class="hljs-string">"
          Congratulations on your new vehicle!
          We hope you enjoy driving it as much as we enjoyed building it.
          "</span><span class="hljs-string">""</span>;
      }
     }
   }
</code></pre>
<p>When we display this string, it's aligned appropriately to the left margin as shown in Figure 3.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/indented-based-on-closing-quote.png" alt="Image" width="600" height="400" loading="lazy">
<em>Figure 3. Raw string literal is indented based on the closing quote</em></p>
<p>Recall that I said that raw string literals start with <strong>at least</strong> three quotes. The C# team wanted the feature to have a long life, so they made it configurable. If for some reason you need triple quotes within the string, you could use quad quotes to enclose the raw string literal. Just be sure that the string ends with the same number of quotes.</p>
<p>A single line raw string literal requires that the opening and closing quotes are on the same line. Here is a single line raw string literal. Notice the three quotation marks at the beginning and ending. Then the embedded quotes don't require any special characters.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">string</span> text = <span class="hljs-string">""</span><span class="hljs-string">"He said, "</span>None shall Pass<span class="hljs-string">"."</span><span class="hljs-string">""</span>
</code></pre>
<p>A multiple line raw string literal requires that the opening quotes are on the line above the raw string and the closing quotes are on their own line below the raw string. Here is a JSON string defined using a raw string literal. Notice that we can use normal quotation marks around the field names and string values. So our JSON looks like JSON.</p>
<pre><code class="lang-csharp">  <span class="hljs-keyword">string</span> vehicleJSON = <span class="hljs-string">""</span><span class="hljs-string">"
    {
      "</span>id<span class="hljs-string">": 1,
      "</span>name<span class="hljs-string">": "</span>AT-AT<span class="hljs-string">",
      "</span>price<span class="hljs-string">": 19416.13
    }
    "</span><span class="hljs-string">""</span>;
</code></pre>
<p>Since the indenting of the raw string literal is defined by the start of the closing quotes, the text must <strong>not</strong> be outdented from that closing set of quotes.</p>
<p>The example below has the ending curly brace to the left of the closing quotes. So this code generates a syntax error as shown in Figure 4.</p>
<pre><code class="lang-csharp">  <span class="hljs-keyword">string</span> vehicleJSON = <span class="hljs-string">""</span><span class="hljs-string">"
    {
      "</span>id<span class="hljs-string">": 1,
      "</span>name<span class="hljs-string">": "</span>AT-AT<span class="hljs-string">",
      "</span>price<span class="hljs-string">": 19416.13
  }
    "</span><span class="hljs-string">""</span>;
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/error-message.png" alt="Image" width="600" height="400" loading="lazy">
<em>Figure 4. Error message when raw string literal is outdented beyond the closing quotes</em></p>
<p>Use raw string literals instead of verbatim strings when working with multiple lines or strings with quotes or other special characters that require escape sequences.</p>
<p>With the power, flexibility, and clarity of the raw string literals, you may never use a verbatim string literal again!</p>
<h2 id="heading-string-interpolation"><strong>String Interpolation</strong></h2>
<p>We often want to include the value of a variable or expression within a string. That's the purpose of interpolation. String interpolation allows us to insert an expression into a string literal.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">string</span> pageTitle = <span class="hljs-string">"Vehicle Detail"</span>;
<span class="hljs-keyword">string</span> header = <span class="hljs-string">$"Header: <span class="hljs-subst">{pageTitle}</span>"</span>;
</code></pre>
<p>We identify an interpolated string with a dollar sign in front of the first quote. We add one or more expressions into the string using curly braces. The curly braces act as a placeholder. </p>
<p>At runtime, the expression is evaluated and the appropriate value appears in the string in place of the curly braces and expression. This way we can embed the value of a variable or expression in a string literal.</p>
<p>Here are some examples. We can include a calculation or call a method. Any valid C# expression can be inserted within the curly braces.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">string</span> answer = <span class="hljs-string">$"Answer: <span class="hljs-subst">{ <span class="hljs-number">20</span> * <span class="hljs-number">2</span> + <span class="hljs-number">2</span> }</span>"</span>;

<span class="hljs-keyword">string</span> pageTitle = <span class="hljs-string">"Vehicle Detail"</span>;
<span class="hljs-keyword">string</span> header = <span class="hljs-string">$"Header: <span class="hljs-subst">{PrepareTitle(pageTitle)}</span>"</span>;
</code></pre>
<h3 id="heading-constant-string-interpolation-new-in-c-10">Constant String Interpolation (New in C# 10)</h3>
<p>As of C# 10, we can define an interpolated string as a constant ... but only if the interpolated expression is a constant, like in this example.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">const</span> <span class="hljs-keyword">string</span> pageTitle = <span class="hljs-string">"Vehicle Detail"</span>;
<span class="hljs-keyword">const</span> <span class="hljs-keyword">string</span> header = <span class="hljs-string">$"Header: <span class="hljs-subst">{pageTitle}</span>"</span>;
</code></pre>
<p>Since the interpolated expression is a constant in this example, the interpolated string can be defined as a constant. This may not be a very common requirement, but it's nice to know the feature is available if you should need it.</p>
<h2 id="heading-newlines-in-interpolation-expressions-new-in-c-11">Newlines in Interpolation Expressions (New in C# 11)</h2>
<p>New in C# 11, we can use multiline interpolated expressions. This can make code within the curly braces a bit easier to read. </p>
<p>In this example, we're using the ternary conditional operator. If the page title variable is empty, we set "no title", otherwise we set the page title. Notice that we must enclose the ternary conditional operator in parentheses within the curly braces.</p>
<pre><code class="lang-csharp">    <span class="hljs-keyword">string</span> pageTitle = <span class="hljs-string">""</span>;

    <span class="hljs-keyword">string</span> header = <span class="hljs-string">$"Header: <span class="hljs-subst">{
      (pageTitle == <span class="hljs-string">""</span>
        ? <span class="hljs-string">"No title"</span>
        : pageTitle)
    }</span>"</span>;
</code></pre>
<p>Putting too much code inside of an interpolation expression makes that code hard to debug and test. So be careful how much code you write within the interpolated expression. In some cases, it may be better to put the code in a function and call that function from the interpolated expression</p>
<h2 id="heading-verbatim-string-interpolation"><strong>Verbatim String Interpolation</strong></h2>
<p>We can combine string interpolation with verbatim strings using <code>@$</code> or <code>$@</code>. That way we can have multiple lines of text and optionally, multiple lines for our interpolation expression.</p>
<pre><code class="lang-csharp">    <span class="hljs-keyword">string</span> pageTitle = <span class="hljs-string">"Vehicle Detail"</span>;
    <span class="hljs-keyword">string</span> header = @<span class="hljs-string">$"
      &lt;div class="</span><span class="hljs-string">"card"</span><span class="hljs-string">"&gt;
        &lt;div class="</span><span class="hljs-string">"card-header"</span><span class="hljs-string">"&gt;
          {(pageTitle == "</span><span class="hljs-string">"
           ? "</span>No title<span class="hljs-string">"
           : pageTitle)}
        &lt;/div&gt;
      &lt;/div&gt;
    "</span>;
</code></pre>
<p>But since it is a verbatim string, we again need double quotes for any embedded quotes.</p>
<h2 id="heading-raw-string-interpolation-new-in-c-11"><strong>Raw String Interpolation (New in C# 11)</strong></h2>
<p>A better option for string interpolation is raw string interpolation, available in C# 11. Here we add the dollar sign in front of our three sets of quotation marks. Then we can define multiple lines of text and multiple lines for our interpolation expression.</p>
<pre><code class="lang-csharp"> <span class="hljs-keyword">string</span> pageTitle = <span class="hljs-string">"Vehicle Detail"</span>;
  <span class="hljs-keyword">string</span> header = <span class="hljs-string">$""</span><span class="hljs-string">"
      &lt;div class="</span>card<span class="hljs-string">"&gt;
        &lt;div class="</span>card-header<span class="hljs-string">"&gt;
          {(pageTitle == "</span><span class="hljs-string">"
           ? "</span>No title<span class="hljs-string">"
           : pageTitle)}
        &lt;/div&gt;
      &lt;/div&gt;
    "</span><span class="hljs-string">""</span>;
</code></pre>
<p>Let's look at another example, creating a JSON string. This is the string we want to create. But we want to use interpolation for the price instead of hardcoding it.</p>
<pre><code class="lang-csharp">   {
      <span class="hljs-string">"id"</span>: <span class="hljs-number">1</span>,
      <span class="hljs-string">"name"</span>: <span class="hljs-string">"AT-AT"</span>,
      <span class="hljs-string">"price"</span>: <span class="hljs-number">19416.13</span>
    }
</code></pre>
<p>Notice that JSON syntax requires curly braces around the object. But if we want to use an interpolated string, the interpolation needs curly braces. So are we going to need to escape those curly braces? Nope!</p>
<p>The C# team wanted a string interpolation solution that was configurable. So for raw string interpolation, we can optionally use <strong>two</strong> dollar signs. The <strong>two</strong> dollar signs means that we need <strong>two</strong> sets of curly braces for the interpolation. That way the single set of curly braces can be interpreted as part of the string literal.</p>
<pre><code class="lang-csharp">    <span class="hljs-keyword">decimal</span> price = <span class="hljs-number">19416.13</span>M;
    <span class="hljs-keyword">string</span> vehicleJSON = $<span class="hljs-string">$""</span><span class="hljs-string">"
      {
        "</span>id<span class="hljs-string">": 1,
        "</span>name<span class="hljs-string">": "</span>AT-AT<span class="hljs-string">",
        "</span>price<span class="hljs-string">": {{price}}
      }
      "</span><span class="hljs-string">""</span>;
</code></pre>
<p>Or we could use three dollar signs with three sets of curly braces, and so on. The number of dollar signs indicates the number of pairs of curly braces required for interpolation.</p>
<p>Very cool!</p>
<h2 id="heading-wrapping-up"><strong>Wrapping Up</strong></h2>
<p>This tutorial walked through options for defining string literals and for string interpolation.</p>
<p>The new raw string literal and raw string interpolation simplify string management, offering a flexible solution for working with strings.</p>
<p>Check out the video here:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/A5FRgglBkJ8" 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>Or try out the <a target="_blank" href="https://github.com/DeborahK/CSharp-Examples">sample code here</a>. </p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
