<?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" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[C# Snaps: Sharp Bites for Better Code - Medium]]></title>
        <description><![CDATA[Welcome to C# Snaps — your go-to destination for crisp, clear, and practical C# knowledge bytes. Whether you’re just starting your journey or want to sharpen your coding edge, each post delivers hands-on examples, real-world tips, and bite-sized insights you can grasp in minutes. - Medium]]></description>
        <link>https://medium.com/c-snaps-sharp-bites-for-better-code?source=rss----82811fb2bb53---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>C# Snaps: Sharp Bites for Better Code - Medium</title>
            <link>https://medium.com/c-snaps-sharp-bites-for-better-code?source=rss----82811fb2bb53---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 01:04:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/c-snaps-sharp-bites-for-better-code" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[FrozenDictionary and FrozenSet: When Read-Heavy Lookups Deserve a Different Collection]]></title>
            <link>https://medium.com/c-snaps-sharp-bites-for-better-code/frozendictionary-and-frozenset-when-read-heavy-lookups-deserve-a-different-collection-e87cf9a76b43?source=rss----82811fb2bb53---4</link>
            <guid isPermaLink="false">https://medium.com/p/e87cf9a76b43</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding-instructions]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Sauradipta]]></dc:creator>
            <pubDate>Fri, 13 Nov 2026 06:30:01 GMT</pubDate>
            <atom:updated>2026-11-13T06:30:02.432Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*thPNr1CG64F3amkln39lRw.png" /></figure><h3>They aren’t replacements for Dictionary and HashSet. They’re optimized for a different lifecycle: build once, read repeatedly.</h3><p>Imagine an application with a configuration table:</p><pre>var countryCodes = new Dictionary&lt;string, string&gt;<br>{<br>    [&quot;IN&quot;] = &quot;India&quot;,<br>    [&quot;US&quot;] = &quot;United States&quot;,<br>    [&quot;GB&quot;] = &quot;United Kingdom&quot;,<br>    [&quot;DE&quot;] = &quot;Germany&quot;<br>};</pre><p>The application might perform this lookup thousands or millions of times. But here’s the interesting part:</p><blockquote><strong>The dictionary never changes after startup.</strong></blockquote><p>So why are we using a mutable collection?</p><p>This is exactly the kind of scenario where FrozenDictionary&lt;TKey,TValue&gt; becomes interesting.</p><p>A normal dictionary is the obvious choice:</p><pre>var statusDescriptions = new Dictionary&lt;int, string&gt;<br>{<br>    [200] = &quot;Success&quot;,<br>    [400] = &quot;Bad Request&quot;,<br>    [404] = &quot;Not Found&quot;,<br>    [500] = &quot;Server Error&quot;<br>};<br>var description = statusDescriptions[404];</pre><blockquote>Dictionary&lt;TKey,TValue&gt; is excellent at what it does.</blockquote><p>It supports:</p><ul><li>adding entries</li></ul><p>adding entries</p><p>removing entries</p><ul><li>updating values</li><li>looking up keys</li><li>enumerating entries</li></ul><p>It’s a general-purpose mutable dictionary.</p><pre>Application starts<br>       ↓<br>Load configuration<br>       ↓<br>Build dictionary<br>       ↓<br>Dictionary never changes<br>       ↓<br>Thousands of lookups</pre><p>The <strong><em>mutability </em></strong>that makes Dictionary flexible isn&#39;t providing much value anymore.</p><p>That’s where frozen collections enter the picture.</p><h3>What is a FrozenDictionary?</h3><p>FrozenDictionary&lt;TKey,TValue&gt; is a read-only dictionary optimized for fast lookup and enumeration.</p><p>The important word isn’t <strong>frozen</strong>. It’s <strong><em>optimized</em></strong>.</p><pre>using System.Collections.Frozen;<br><br>var statusDescriptions = new Dictionary&lt;int, string&gt;<br>{<br>    [200] = &quot;Success&quot;,<br>    [400] = &quot;Bad Request&quot;,<br>    [404] = &quot;Not Found&quot;,<br>    [500] = &quot;Server Error&quot;<br>};<br><br>var frozenStatuses = statusDescriptions.ToFrozenDictionary();<br>var description = frozenStatuses[404];</pre><p>The resulting collection cannot be modified.</p><p>More importantly, creating the frozen collection is allowed to do additional work up front so that the resulting structure can be optimized for its intended read-heavy workload. Microsoft explicitly describes FrozenDictionary as having a relatively high creation cost but excellent lookup performance. <em>[Reference: </em><a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.frozen.frozendictionary-2?utm_source=chatgpt.com"><em>Microsoft Learn</em></a><em>]</em></p><h3>FrozenSet follows the same idea</h3><p>The same concept exists for sets.</p><p>Suppose you have a collection of supported feature flags:</p><pre>var supportedFeatures = new HashSet&lt;string&gt;<br>{<br>    &quot;Search&quot;,<br>    &quot;Reports&quot;,<br>    &quot;Export&quot;,<br>    &quot;Notifications&quot;<br>};</pre><p>And your application repeatedly asks:</p><pre>if (supportedFeatures.Contains(feature))<br>{<br>    ...<br>}</pre><p>If the set never changes after initialization, you can freeze it:</p><pre>var frozenFeatures = supportedFeatures.ToFrozenSet();<br>if (frozenFeatures.Contains(feature))<br>{<br>    ...<br>}</pre><p>FrozenSet&lt;T&gt; is the read-only counterpart optimized for lookup and enumeration. <em>[Reference: </em><a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.frozen?utm_source=chatgpt.com"><em>Microsoft Learn</em></a><em>]</em></p><h3>Why not just use IReadOnlyDictionary?</h3><p>This is an important distinction.</p><p>You might think:</p><pre>IReadOnlyDictionary&lt;int, string&gt; statuses =<br>    new Dictionary&lt;int, string&gt;<br>    {<br>        [200] = &quot;Success&quot;,<br>        [404] = &quot;Not Found&quot;<br>    };</pre><p>Now consumers can’t modify the dictionary through the interface. But that doesn’t mean the underlying dictionary is immutable. Another reference could still modify it:</p><pre>var dictionary = new Dictionary&lt;int, string&gt;<br>{<br>    [200] = &quot;Success&quot;<br>};<br><br>IReadOnlyDictionary&lt;int, string&gt; readOnly = dictionary;<br><br>dictionary[500] = &quot;Server Error&quot;;</pre><p>The IReadOnlyDictionary interface restricts what the <strong>consumer can do through that reference</strong>. It doesn’t transform the underlying collection. A frozen collection is different. Once created, its contents are fixed.</p><h3>What about ReadOnlyDictionary?</h3><p>ReadOnlyDictionary&lt;TKey,TValue&gt; also provides a read-only wrapper.</p><p>For example:</p><pre>var dictionary = new Dictionary&lt;string, int&gt;<br>{<br>    [&quot;Low&quot;] = 1,<br>    [&quot;High&quot;] = 2<br>};<br><br>var readOnly = new ReadOnlyDictionary&lt;string, int&gt;(dictionary);</pre><p>But the wrapper still reflects changes made to the underlying dictionary.</p><p>So there are three different ideas worth separating:</p><pre>Dictionary<br>    Mutable collection<br><br>IReadOnlyDictionary<br>    Read-only view/interface<br><br>ReadOnlyDictionary<br>    Read-only wrapper around another dictionary<br><br>FrozenDictionary<br>    Immutable collection optimized for repeated reads</pre><p>Those are not interchangeable concepts.</p><h3>The real question: how often does the data change?</h3><p>This is the decision point I would use in real applications.</p><p>Ask:</p><blockquote><strong><em>How frequently is this collection rebuilt or modified relative to how frequently it is read?</em></strong></blockquote><p>Consider collections for — Feature Flags, Country Metadata, HTTP Status Description.</p><blockquote><strong>Good frozen-collection candidates.</strong></blockquote><p>User Session State — Frequently updated after creation.</p><blockquote><strong>Not a frozen-collection candidate.</strong></blockquote><h3><strong>The mistake: freezing everything</strong></h3><p>This is where performance advice can go wrong. A frozen collection deliberately pays extra work when it is created. Freezing every collection and then perform only a few lookups, you may have gained nothing.</p><p>You might actually have made the application slower.</p><p>The optimization makes sense when the construction cost is amortized over enough reads.</p><p>Microsoft’s documentation describes the ideal scenario as a dictionary that is created infrequently but used frequently. <a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.frozen.frozendictionary-2?utm_source=chatgpt.com">[Reference: Microsoft]</a></p><h4><strong>What happens during </strong><strong>ToFrozenDictionary()?</strong></h4><p>Conceptually, you’re telling .NET:</p><blockquote><em>“I’m done changing this collection. You can now optimize its internal representation for the way I’m going to use it.”</em></blockquote><p>For example:</p><pre>var frozen = source.ToFrozenDictionary();</pre><p>The source is enumerated and the frozen collection is constructed. Microsoft’s documentation notes that the details of the keys affect construction time and recommends initializing it with trusted keys. <em>[Reference: </em><a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.frozen.frozendictionary-2?utm_source=chatgpt.com"><em>Microsoft Learn</em></a><em>]</em></p><p>This is why you should think of freezing as a <strong>build step</strong>, not as a lightweight cast.</p><h4><strong>A useful startup pattern:</strong></h4><pre>public static class CountryData<br>{<br>    public static readonly FrozenDictionary&lt;string, string&gt; Names =<br>        new Dictionary&lt;string, string&gt;<br>        {<br>            [&quot;IN&quot;] = &quot;India&quot;,<br>            [&quot;US&quot;] = &quot;United States&quot;,<br>            [&quot;GB&quot;] = &quot;United Kingdom&quot;,<br>            [&quot;JP&quot;] = &quot;Japan&quot;<br>        }<br>        .ToFrozenDictionary();<br>}</pre><p>The expensive part happens once. The application then performs lookups throughout its lifetime. That’s the workload frozen collections were designed for.</p><h3>It also improves the API contract</h3><p>Compare these two fields:</p><pre>private readonly Dictionary&lt;string, Handler&gt; _handlers;</pre><p>and:</p><pre>private readonly FrozenDictionary&lt;string, Handler&gt; _handlers;</pre><p>The second one tells the reader something immediately:</p><p><strong>This collection is intentionally fixed after initialization. </strong>That is useful even before we talk about performance. Good collection choices communicate design intent.</p><h4><strong>Frozen collections are not just about immutability</strong></h4><p>If all you need is immutability, don’t assume frozen collections are automatically the best answer.</p><p>The reason to consider them is the combination of:</p><blockquote><strong>immutable + read-heavy + optimized lookup/enumeration</strong></blockquote><p>That’s a more specific use case.</p><h3>What about enumeration?</h3><p>Frozen collections are also optimized for enumeration, not only key lookup. Microsoft describes both FrozenDictionary and FrozenSet as optimized for fast lookup <strong>and enumeration</strong>. <em>[Reference: </em><a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.frozen?utm_source=chatgpt.com"><em>Microsoft Learn</em></a><em>]</em></p><p>That makes them useful for static datasets such as:</p><ul><li>protocol mappings</li><li>MIME-type mappings</li><li>country metadata</li><li>feature definitions</li><li>validation rules</li><li>static routing tables</li><li>keyword tables</li><li>application configuration</li><li>lookup tables</li></ul><p>But the key characteristic is still the same:</p><blockquote><strong>The data is established infrequently and consumed repeatedly.</strong></blockquote><h3>When ImmutableDictionary might be better</h3><p>Suppose you need a collection that cannot be modified in place, but you frequently create updated versions:</p><pre>Version 1<br>    ↓<br>Version 2<br>    ↓<br>Version 3<br>    ↓<br>Version 4</pre><p>An immutable collection may be a better fit.</p><p>The distinction is:</p><pre>FrozenDictionarytype<br>    Build once<br>    Read many times<br><br>ImmutableDictionary<br>    Never mutate an instance<br>    Create new versions as needed<br><br>Dictionary<br>    Mutate as needed</pre><p>That is a much more useful way to choose between them than simply asking which one is “fastest.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*cf6EnielKgcSsx-T0ZpYwQ.png" /></figure><p>The exact performance characteristics depend on your workload, key types, comparer, collection size, and access pattern.</p><p>For performance-sensitive code, benchmark the actual workload rather than relying on a generic claim.</p><h3>When should you use FrozenDictionary or FrozenSet?</h3><p>Use them when:</p><ul><li>the collection is created infrequently</li><li>the contents don’t change afterward</li><li>lookup is frequent</li><li>enumeration is frequent</li><li>the collection has a meaningful lifetime</li><li>you want the type itself to communicate that the data is fixed</li><li>profiling or workload characteristics justify the construction cost</li></ul><p>Typical examples include:</p><pre>Application startup configuration<br>Static lookup tables<br>Protocol mappings<br>Feature metadata<br>Validation tables<br>Routing metadata<br>Frequently queried reference data</pre><h3>When should you NOT use them?</h3><p>Avoid frozen collections when:</p><ul><li>the collection changes frequently</li><li>you rebuild it often</li><li>you perform only a small number of lookups</li><li>the collection is short-lived</li><li>you need efficient incremental updates</li><li>you’re choosing it purely because “frozen sounds faster”</li><li>you haven’t established that lookup performance matters</li></ul><p>And most importantly:</p><p><strong>Don’t introduce a frozen collection into a hot path that repeatedly rebuilds it.</strong></p><p>That defeats the whole design.</p><h3>Key takeaway</h3><p>FrozenDictionary&lt;TKey,TValue&gt; and FrozenSet&lt;T&gt; aren&#39;t replacements for Dictionary&lt;TKey,TValue&gt; and HashSet&lt;T&gt;.</p><p>They’re specialized tools for a specific workload:</p><blockquote><strong><em>Build infrequently. Don’t modify. Read frequently.</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e87cf9a76b43" width="1" height="1" alt=""><hr><p><a href="https://medium.com/c-snaps-sharp-bites-for-better-code/frozendictionary-and-frozenset-when-read-heavy-lookups-deserve-a-different-collection-e87cf9a76b43">FrozenDictionary and FrozenSet: When Read-Heavy Lookups Deserve a Different Collection</a> was originally published in <a href="https://medium.com/c-snaps-sharp-bites-for-better-code">C# Snaps: Sharp Bites for Better Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C# 14 Extension Members: What Changes When Extensions Become More Than Methods?]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/c-snaps-sharp-bites-for-better-code/c-14-extension-members-what-changes-when-extensions-become-more-than-methods-25fb1bc16baa?source=rss----82811fb2bb53---4"><img src="https://cdn-images-1.medium.com/max/1774/1*NZUCnC1OCX7OLVn9uuIbsA.png" width="1774"></a></p><p class="medium-feed-snippet">Extension methods have been around for years. C# 14 finally expands the idea beyond methods &#x2014; but that doesn&#x2019;t mean you should use&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/c-snaps-sharp-bites-for-better-code/c-14-extension-members-what-changes-when-extensions-become-more-than-methods-25fb1bc16baa?source=rss----82811fb2bb53---4">Continue reading on C# Snaps: Sharp Bites for Better Code »</a></p></div>]]></description>
            <link>https://medium.com/c-snaps-sharp-bites-for-better-code/c-14-extension-members-what-changes-when-extensions-become-more-than-methods-25fb1bc16baa?source=rss----82811fb2bb53---4</link>
            <guid isPermaLink="false">https://medium.com/p/25fb1bc16baa</guid>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Sauradipta]]></dc:creator>
            <pubDate>Sun, 04 Oct 2026 15:58:20 GMT</pubDate>
            <atom:updated>2026-10-04T15:58:22.376Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Stop Writing Backing Fields for Every Property: Meet field in C# 14]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/c-snaps-sharp-bites-for-better-code/stop-writing-backing-fields-for-every-property-meet-field-in-c-14-8a2369fcf359?source=rss----82811fb2bb53---4"><img src="https://cdn-images-1.medium.com/max/1942/1*WuA4a9Jj5ZhzLiSNyuAGFw.png" width="1942"></a></p><p class="medium-feed-snippet">C# 14 makes the journey from an auto-property to a validated property much cleaner &#x2014; but that doesn&#x2019;t mean every property should use field.</p><p class="medium-feed-link"><a href="https://medium.com/c-snaps-sharp-bites-for-better-code/stop-writing-backing-fields-for-every-property-meet-field-in-c-14-8a2369fcf359?source=rss----82811fb2bb53---4">Continue reading on C# Snaps: Sharp Bites for Better Code »</a></p></div>]]></description>
            <link>https://medium.com/c-snaps-sharp-bites-for-better-code/stop-writing-backing-fields-for-every-property-meet-field-in-c-14-8a2369fcf359?source=rss----82811fb2bb53---4</link>
            <guid isPermaLink="false">https://medium.com/p/8a2369fcf359</guid>
            <category><![CDATA[csharp-14]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Sauradipta]]></dc:creator>
            <pubDate>Mon, 21 Sep 2026 17:54:02 GMT</pubDate>
            <atom:updated>2026-09-21T17:54:03.964Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[ Beyond the Basics: 5 Switch Expression Patterns Every C# Developer Should Know]]></title>
            <link>https://medium.com/c-snaps-sharp-bites-for-better-code/beyond-the-basics-5-switch-expression-patterns-every-c-developer-should-know-e703d7bf3e95?source=rss----82811fb2bb53---4</link>
            <guid isPermaLink="false">https://medium.com/p/e703d7bf3e95</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[code-quality]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Sauradipta]]></dc:creator>
            <pubDate>Mon, 13 Jul 2026 06:34:48 GMT</pubDate>
            <atom:updated>2026-07-13T06:38:47.704Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*3eRKC6PX78iNlnLXWrK3UA.png" /></figure><blockquote>Think you’ve mastered switch expressions? These five patterns will help you write cleaner, safer, and more maintainable C# code.</blockquote><p>In my previous article, <a href="https://medium.com/c-snaps-sharp-bites-for-better-code/avoid-the-if-else-jungle-use-switch-expressions-like-a-pro-f07f324935e0"><strong>“Avoid the if-else Jungle: Use Switch Expressions Like a Pro,”</strong></a> we explored how switch expressions can replace long if-else chains.</p><p>But that was just the beginning.</p><p>Modern C# has evolved significantly since switch expressions were introduced. Today, they work seamlessly with pattern matching and other language features, allowing you to write code that’s not only concise but also expressive and resilient.</p><p>Let’s look at five patterns that experienced C# developers use every day.</p><h4>1️⃣ Prefer Enums Over Strings</h4><p>A common beginner mistake is comparing strings.</p><pre>public decimal GetDiscount(string customerType) =&gt;<br>    customerType switch<br>    {<br>        &quot;Regular&quot; =&gt; 0.10m,<br>        &quot;Premium&quot; =&gt; 0.20m,<br>        &quot;VIP&quot; =&gt; 0.30m,<br>        _ =&gt; 0m<br>    };</pre><p>Although this works, it comes with several drawbacks:</p><ul><li>Typos aren’t caught by the compiler.</li><li>Refactoring becomes harder.</li><li>String comparisons are slower than enum comparisons.</li><li>Invalid values can easily sneak into your application.</li></ul><p>Instead, define an enum.</p><pre>public enum CustomerType<br>{<br>    Regular,<br>    Premium,<br>    Vip<br>}</pre><p>Now your switch becomes:</p><pre>public decimal GetDiscount(CustomerType customerType) =&gt;<br>    customerType switch<br>    {<br>        CustomerType.Regular =&gt; 0.10m,<br>        CustomerType.Premium =&gt; 0.20m,<br>        CustomerType.Vip =&gt; 0.30m<br>    };</pre><p>Notice something? There is <strong>no default case</strong>. That’s intentional.</p><p>💡 <strong>Code Review Tip</strong></p><blockquote>If your possible values are known beforehand, use an <strong>enum</strong> instead of strings. Your compiler becomes your first line of defense.</blockquote><h4>2️⃣ <strong>Let the Compiler Catch Missing Cases</strong></h4><p>One of the biggest advantages of switch expressions is <strong>exhaustiveness checking</strong>.</p><p>Suppose your enum grows.</p><pre>public enum CustomerType<br>{<br>    Regular,<br>    Premium,<br>    Vip,<br>    Corporate<br>}</pre><p>Your existing switch expression now becomes incomplete.</p><pre>public decimal GetDiscount(CustomerType customerType) =&gt;<br>    customerType switch<br>    {<br>        CustomerType.Regular =&gt; 0.10m,<br>        CustomerType.Premium =&gt; 0.20m,<br>        CustomerType.Vip =&gt; 0.30m<br>    };</pre><p>Instead of silently returning the wrong value, the compiler warns you that not all enum values are handled.</p><p>That’s incredibly valuable in large codebases.</p><p>It means adding a new enum member immediately highlights every place where business logic needs updating.</p><p>Without exhaustive switches, these bugs often remain hidden until production.</p><p>💡 <strong>Code Review Tip</strong></p><blockquote>Avoid adding _ =&gt; ... simply out of habit.</blockquote><blockquote>If every possible enum value should be handled explicitly, let the compiler warn you when new values are introduced.</blockquote><h4>3️⃣ Match Objects, Not Just Values</h4><p>Switch expressions become much more powerful when combined with <strong>property patterns</strong>.</p><p>Imagine an online shopping application.</p><pre>public record Order(decimal Amount, bool IsPremiumCustomer);</pre><p>Now determining shipping becomes straightforward.</p><pre>public static string GetShipping(Order order) =&gt;<br>    order switch<br>    {<br>        { Amount: &gt;= 1000, IsPremiumCustomer: true } =&gt; &quot;Free Express Shipping&quot;,<br><br>        { Amount: &gt;= 1000 } =&gt; &quot;Free Standard Shipping&quot;,<br><br>        { IsPremiumCustomer: true } =&gt; &quot;Discounted Shipping&quot;,<br><br>        _ =&gt; &quot;Standard Shipping&quot;<br>    };</pre><p>Instead of writing multiple nested if statements, you&#39;re describing the characteristics of the object you&#39;re interested in.</p><p>This style reads almost like business requirements.</p><p><strong>Why it matters?</strong></p><blockquote>Property patterns reduce nested logic while making business rules easier to understand.</blockquote><blockquote>They’re especially useful in APIs, rule engines, pricing systems, and workflow applications.</blockquote><h4>4️⃣ Use Relational Patterns for Ranges</h4><p>Range-based conditions are another area where switch expressions shine.</p><p>Consider grading students.</p><pre>public static string GetGrade(int marks) =&gt;<br>    marks switch<br>    {<br>        &gt;= 90 =&gt; &quot;A&quot;,<br>        &gt;= 75 =&gt; &quot;B&quot;,<br>        &gt;= 60 =&gt; &quot;C&quot;,<br>        &gt;= 40 =&gt; &quot;D&quot;,<br>        _ =&gt; &quot;F&quot;<br>    };</pre><p>Compare this with several nested if statements. The intent is immediately obvious. You can also combine conditions.</p><pre>public static string GetAgeCategory(int age) =&gt;<br>    age switch<br>    {<br>        &gt;= 0 and &lt; 13 =&gt; &quot;Child&quot;,<br><br>        &gt;= 13 and &lt; 20 =&gt; &quot;Teenager&quot;,<br><br>        &gt;= 20 and &lt; 60 =&gt; &quot;Adult&quot;,<br><br>        _ =&gt; &quot;Senior Citizen&quot;<br>    };</pre><p><strong>Readable — Concise — Easy to maintain</strong></p><p><strong>💡 Code Review Tip</strong></p><blockquote>Whenever you find yourself writing multiple range checks, ask yourself:</blockquote><blockquote><strong>Can this become a switch expression?</strong></blockquote><blockquote>Often, the answer is yes.</blockquote><h4>5️⃣ A Real-World Example: HTTP Status Messages</h4><p>Toy examples are useful for learning, but let’s look at something you’ll actually encounter.</p><pre>public enum HttpStatus<br>{<br>    Ok,<br>    BadRequest,<br>    Unauthorized,<br>    NotFound,<br>    InternalServerError<br>}</pre><p>Now map each status to a user-friendly message.</p><pre>public static string GetMessage(HttpStatus status) =&gt;<br>    status switch<br>    {<br>        HttpStatus.Ok =&gt; &quot;Request completed successfully.&quot;,<br><br>        HttpStatus.BadRequest =&gt; &quot;The request is invalid.&quot;,<br><br>        HttpStatus.Unauthorized =&gt; &quot;Please sign in to continue.&quot;,<br><br>        HttpStatus.NotFound =&gt; &quot;The requested resource was not found.&quot;,<br><br>        HttpStatus.InternalServerError =&gt; &quot;Something went wrong on our side.&quot;<br>    };</pre><p>This is exactly the kind of value mapping switch expressions were designed for.</p><p><strong>Simple — Readable — Maintainable</strong></p><h4>❌ When NOT to Use Switch Expressions?</h4><p>Switch expressions aren’t the answer to every problem.</p><p>Avoid them when each branch performs multiple actions.</p><p>For example:</p><pre>if (paymentSucceeded)<br>{<br>    SaveOrder();<br><br>    SendEmail();<br><br>    LogSuccess();<br><br>    UpdateInventory();<br>}</pre><p>Trying to force this into a switch expression would hurt readability.</p><p>Switch expressions work best when your goal is to <strong>map one value to another</strong>.</p><p>If you’re executing multiple operations, a traditional switch statement or if-else chain is often the better choice.</p><p>Choosing the right tool is just as important as knowing the latest language feature.</p><h4>Key Takeaways</h4><p>✅ Prefer enums over strings whenever possible.</p><p>✅ Let the compiler tell you when you’ve missed a case.</p><p>✅ Use property patterns for object-based decisions.</p><p>✅ Use relational patterns for ranges.</p><p>✅ Use switch expressions for value mapping — not complex workflows.</p><h4>🧩 Try It Yourself!</h4><p>Refactor one of these methods in your current project using a switch expression:</p><ul><li>GetOrderStatusMessage()</li><li>GetShippingMethod()</li><li>CalculateTaxRate()</li><li>GetUserRoleDescription()</li><li>GetNotificationIcon()</li></ul><p>You might be surprised by how much cleaner the code becomes.</p><h4>📚 Related Reading</h4><p>If you’re new to switch expressions, start with:</p><p><a href="https://medium.com/c-snaps-sharp-bites-for-better-code/avoid-the-if-else-jungle-use-switch-expressions-like-a-pro-f07f324935e0">➡️ <strong>Avoid the if-else Jungle: Use Switch Expressions Like a Pro</strong></a></p><p>It covers the fundamentals before diving into the advanced patterns discussed here.</p><h3>Final Thoughts</h3><p>Modern C# isn’t about writing less code — it’s about writing <strong>clearer code</strong>.</p><p>Switch expressions, combined with pattern matching, help you express business rules in a way that’s easier to read, review, and maintain. That’s why they’ve become a staple in production codebases.</p><p>If this article helped you, consider following <strong>C# Snaps</strong> for more bite-sized, practical C# tips. Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e703d7bf3e95" width="1" height="1" alt=""><hr><p><a href="https://medium.com/c-snaps-sharp-bites-for-better-code/beyond-the-basics-5-switch-expression-patterns-every-c-developer-should-know-e703d7bf3e95">🚀 Beyond the Basics: 5 Switch Expression Patterns Every C# Developer Should Know</a> was originally published in <a href="https://medium.com/c-snaps-sharp-bites-for-better-code">C# Snaps: Sharp Bites for Better Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Avoid the if-else Jungle: Use Switch Expressions Like a Pro]]></title>
            <link>https://medium.com/c-snaps-sharp-bites-for-better-code/avoid-the-if-else-jungle-use-switch-expressions-like-a-pro-f07f324935e0?source=rss----82811fb2bb53---4</link>
            <guid isPermaLink="false">https://medium.com/p/f07f324935e0</guid>
            <category><![CDATA[if-else]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[switch]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Sauradipta]]></dc:creator>
            <pubDate>Sat, 10 May 2025 16:57:25 GMT</pubDate>
            <atom:updated>2026-07-13T06:36:39.596Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*3eRKC6PX78iNlnLXWrK3UA.png" /></figure><p>Tired of messy if-else chains? You&#39;re not alone. In modern C# (8.0 and above), <strong>switch expressions</strong> offer a cleaner, more readable, and more concise way to handle conditional logic.</p><p>In this quick byte, we’ll walk through:</p><ul><li>Why switch expressions matter</li><li>Syntax comparison</li><li>Real-world examples</li><li>Bonus: pattern matching with switch expressions</li></ul><h3>🌴 The Old Jungle: Classic if-else Chains</h3><p>Let’s say you’re calculating discounts based on customer type:</p><pre>public decimal GetDiscount(string customerType)<br>{<br>    if (customerType == &quot;Regular&quot;)<br>        return 0.1m;<br>    else if (customerType == &quot;Premium&quot;)<br>        return 0.2m;<br>    else if (customerType == &quot;VIP&quot;)<br>        return 0.3m;<br>    else<br>        return 0.0m;<br>}</pre><p>This works, but it’s verbose and gets messier as conditions grow.</p><h3>⚡ Enter: C# 8 Switch Expressions</h3><p>Here’s how the same logic looks using a <strong>switch expression</strong>:</p><pre>public decimal GetDiscount(string customerType) =&gt;<br>    customerType switch<br>    {<br>        &quot;Regular&quot; =&gt; 0.1m,<br>        &quot;Premium&quot; =&gt; 0.2m,<br>        &quot;VIP&quot; =&gt; 0.3m,<br>        _ =&gt; 0.0m<br>    };</pre><p>✅ Cleaner<br>✅ Expression-based (not statement-based)<br>✅ Compiler-enforced exhaustiveness</p><p>🛠️ <strong>Real-World Example: Shipping Cost Calculator</strong></p><pre>public decimal CalculateShipping(string destinationCountry) =&gt;<br>    destinationCountry switch<br>    {<br>        &quot;US&quot; =&gt; 5.99m,<br>        &quot;UK&quot; =&gt; 6.99m,<br>        &quot;India&quot; =&gt; 4.99m,<br>        &quot;Canada&quot; =&gt; 7.99m,<br>        _ =&gt; throw new ArgumentException(&quot;Unsupported destination&quot;)<br>    };</pre><h3>🔍 Bonus: Pattern Matching + Switch Expression</h3><p>Suppose you want to assign risk level based on age:</p><pre>public string GetRiskLevel(int age) =&gt;<br>    age switch<br>    {<br>        &lt; 18 =&gt; &quot;Low&quot;,<br>        &gt;= 18 and &lt; 60 =&gt; &quot;Medium&quot;,<br>        &gt;= 60 =&gt; &quot;High&quot;,<br>        _ =&gt; &quot;Unknown&quot;<br>    };</pre><p>Yes — you can <strong>match ranges</strong> and <strong>conditions</strong> right inside the switch!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*wLNW8IaILlLs-yBIBIM0QQ.png" /></figure><h3>💡 Pro Tip</h3><p>Use switch expressions when:</p><ul><li>You need to map inputs to outputs (like types to values)</li><li>You want less boilerplate code</li><li>You’re applying decision rules</li></ul><blockquote>Switch expressions aren’t just shorter — they’re declarative. Instead of describing how to reach a result using multiple branches, they describe what result each input should produce. That makes the intent immediately obvious.</blockquote><p>❌ <strong>Don’t use switch expressions when:</strong></p><blockquote>Don’t use switch expressions when each branch performs multiple actions, logging, database calls, or other side effects. They’re best suited for mapping one value to another.</blockquote><p>👀<strong>Code Review Tip:</strong></p><blockquote>During code reviews, if you see an if-else chain whose only purpose is to return a value, ask yourself:</blockquote><blockquote><strong>“Can this become a switch expression?”</strong></blockquote><blockquote>In many cases, the answer is yes — and the result is cleaner, easier to read, and simpler to maintain.</blockquote><h3>🧩 Try It Yourself!</h3><p>Refactor a method like GetTaxRate, GetColorCode, or GetStatusMessage using switch expressions. See how much cleaner your code becomes!</p><p>✍️ <em>Have your own cool use case with switch expressions? Share it in the comments or submit a snap for the publication!</em></p><h3>📚 Continue Learning</h3><p>You’ve now learned <strong>how switch expressions replace bulky </strong><strong>if-else chains</strong>.</p><p>Next, discover how experienced C# developers take them further:</p><p><a href="https://medium.com/c-snaps-sharp-bites-for-better-code/beyond-the-basics-5-switch-expression-patterns-every-c-developer-should-know-e703d7bf3e95">➡️ <strong>Beyond the Basics: 5 Switch Expression Patterns Every C# Developer Should Know</strong></a></p><p>In that article you’ll learn:</p><ul><li>Why enums are better than strings</li><li>How compiler exhaustiveness prevents bugs</li><li>Property patterns</li><li>Relational patterns</li><li>Production-ready examples</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f07f324935e0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/c-snaps-sharp-bites-for-better-code/avoid-the-if-else-jungle-use-switch-expressions-like-a-pro-f07f324935e0">🧠 Avoid the if-else Jungle: Use Switch Expressions Like a Pro</a> was originally published in <a href="https://medium.com/c-snaps-sharp-bites-for-better-code">C# Snaps: Sharp Bites for Better Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Beginner’s Guide to ValueTask and Task in C#]]></title>
            <link>https://medium.com/c-snaps-sharp-bites-for-better-code/a-beginners-guide-to-valuetask-and-task-in-c-b92126ad9c1d?source=rss----82811fb2bb53---4</link>
            <guid isPermaLink="false">https://medium.com/p/b92126ad9c1d</guid>
            <category><![CDATA[dotnet-performance]]></category>
            <category><![CDATA[valuetask]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <dc:creator><![CDATA[Sauradipta]]></dc:creator>
            <pubDate>Sat, 10 May 2025 16:31:21 GMT</pubDate>
            <atom:updated>2025-05-10T07:03:19.017Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*yUHpWQvngZQ-eHlKLwpKiQ.png" /></figure><p>Asynchronous programming is a cornerstone of modern C# development, enabling applications to remain responsive and scalable. While most developers are familiar with <strong>Task</strong>, the introduction of <strong>ValueTask</strong> in <strong>.NET Core</strong> 2.1 provides an alternative for optimizing performance in specific scenarios. This guide explains what <strong>ValueTask </strong>is, how it differs from <strong>Task</strong>, and when to use each.</p><h3>What is Task?</h3><p>A Task<strong> </strong>represents an asynchronous operation in C#. It is the most commonly used type for asynchronous methods and is returned by methods marked with the async keyword. A Taskcan:</p><p>• Represent an operation that is still running.</p><p>• Represent a completed operation with a result (Task&lt;T&gt;).</p><ul><li>Be awaited to pause execution until the operation completes.</li></ul><p><strong>Example of </strong>Task:</p><pre>public async Task&lt;int&gt; GetNumberAsync()<br>{<br>    await Task.Delay(1000); // Simulate asynchronous work<br>    return 42;<br>}</pre><h3>What is ValueTask?</h3><p>ValueTaskis a lightweight alternative toTask, introduced to reduce memory allocations in scenarios where the result of an asynchronous operation is often available synchronously. Unlike Task, which always allocates an object on the heap, ValueTask can avoid this allocation when the result is already available.</p><p><strong>Key Characteristics of ValueTask:</strong></p><p>1.<strong> Memory Efficiency:</strong> Avoids heap allocation when the result is synchronous.</p><p>2. <strong>Reusable:</strong> Can represent both synchronous and asynchronous results.</p><p>3. <strong>Single Await:</strong> Should only be awaited once. If you need to await it multiple times, convert it to a Task using .AsTask().</p><h3>When to Use ValueTask vs. Task?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*8GI1-1Xswtoo4xGviv0I4g.png" /><figcaption>Feature wise comparison of Task v/s ValueTask</figcaption></figure><p><strong>Use Task When:</strong></p><p>• The method is always asynchronous.</p><p>• You don’t need to optimize for memory allocations.</p><ul><li>Simplicity and maintainability are more important than performance.</li></ul><p><strong>Use ValueTask When:</strong></p><p>• The result is often available synchronously.</p><p>• Performance is critical, and you want to reduce memory pressure.</p><ul><li>The method is simple and does not involve multiple asynchronous operations.</li></ul><h3>How to Use ValueTask?</h3><p><strong>Example 1: Returning a Synchronous Result</strong></p><p>When the result is immediately available, you can return it wrapped in a ValueTask without incurring the overhead of creating a Task.</p><p>If the result must be computed asynchronously, use Task.Run() and wrap it in a ValueTask.</p><pre>public ValueTask&lt;int&gt; GetNumberAsync(bool returnSynchronously)<br>{<br>    if (returnSynchronously)<br>    {<br>        // Return synchronously without allocating a Task<br>        return new ValueTask&lt;int&gt;(42);<br>    }<br>    else<br>    {<br>        // Return an asynchronous Task wrapped in a ValueTask<br>        return new ValueTask&lt;int&gt;(Task.Run(() =&gt; 42));<br>    }<br>}</pre><p><strong>Example 2: Using ValueTask in a Repository</strong></p><p>In the ProductRepository class, the GetProductsAsync method uses ValueTask to fetch a list of products:</p><p>We await the result inside the method itself instead of leaving it to the caller, since this is a database operation that must complete before further execution. Additionally, we ensure the ValueTask is awaited only once. I shall explain it further in the subsequent sections.</p><pre>public async ValueTask&lt;List&lt;Product&gt;&gt; GetProductsAsync()<br>{<br>    using ITenantDbContextFactory currentDbContextFactory = _tenantDbContextResolver?.GetFactory()<br>        ?? throw new CustomException(ErrorCodeConstants.TenantResolverNull,<br>                                        ErrorCodeConstants.TenantResolverNullMessage,<br>                                        nameof(ProductRepository));<br><br>    using ITenantDbContext currentDbContext = currentDbContextFactory?.CreateDbContext() <br>        ?? throw new CustomException(ErrorCodeConstants.CurrentDbContextFactoryNull,<br>                                        string.Format(ErrorCodeConstants.CurrentDbContextFactoryNullMessage,<br>                                                !string.IsNullOrEmpty(_tenantDbContextResolver.GetTenantId()) ?<br>                                                 _tenantDbContextResolver.GetTenantId() <br>                                                    : &quot;IsEmpty&quot;),<br>                                        nameof(ProductRepository));<br><br>    return await currentDbContext.Products.ToListAsync&lt;Product&gt;();<br>}</pre><h3>Using ValueTask or Task Without async</h3><p>You can return Task or ValueTask without using the async keyword to avoid the overhead of generating a state machine. This is useful for simple methods where the result is already available.</p><p><strong>Example: Using Task Without async</strong></p><pre>public Task&lt;int&gt; GetNumberAsync()<br>{<br>    // Directly return a Task without using async/await<br>    return Task.FromResult(42);<br>}</pre><p><strong>Example: Using ValueTask Without async</strong></p><pre>public ValueTask&lt;int&gt; GetNumberAsync(bool returnSynchronously)<br>{<br>    if (returnSynchronously)<br>    {<br>        // Return synchronously without allocating a Task<br>        return new ValueTask&lt;int&gt;(42);<br>    }<br>    else<br>    {<br>        // Return an asynchronous Task wrapped in a ValueTask<br>        return new ValueTask&lt;int&gt;(Task.Run(() =&gt; 42));<br>    }<br>}</pre><p>In both cases, the calling function can await the result.</p><h3>Common Pitfalls of ValueTask</h3><p><strong>1. Awaiting a ValueTask Multiple Times</strong></p><p>• <strong>Problem</strong>: A ValueTask should only be awaited once.</p><p>• <strong>Why</strong>: Unlike Task, which can be safely awaited multiple times, ValueTask may result in undefined behavior if reused.</p><p>• <strong>Solution</strong>: Convert to Task using .AsTask().</p><p><strong>Example</strong></p><pre>   ValueTask&lt;int&gt; valueTask = GetNumberAsync();<br>   int result1 = await valueTask; // First await is fine<br>   int result2 = await valueTask; // This can cause issues!</pre><p><strong>Fix</strong></p><pre>   ValueTask&lt;int&gt; valueTask = GetNumberAsync();<br>   Task&lt;int&gt; task = valueTask.AsTask();<br>   int result1 = await task;<br>   int result2 = await task; // Safe to await multiple times</pre><p><strong>2. Using ValueTask for Always-Asynchronous Methods</strong></p><ul><li><strong>Problem</strong>: Adds complexity without benefit.</li><li><strong>Why</strong>: ValueTask shines when the result is frequently synchronous.</li><li><strong>Solution</strong>: Use Task instead for purely asynchronous workflows.</li></ul><p><strong>3. Ignoring the ValueTask Result</strong></p><ul><li><strong>Problem</strong>: If you do not await or explicitly handle a ValueTask, the operation may not complete, leading to resource leaks or incomplete operations.</li><li><strong>Why</strong>: Unlike Task, which can be awaited or ignored safely in some cases, ValueTask<strong> </strong>requires explicit handling.</li><li><strong>Solution</strong>: Always await or handle the ValueTask result.</li></ul><p><strong>Example</strong></p><pre>   ValueTask&lt;int&gt; valueTask = GetNumberAsync();<br>   // Forgetting to await or handle the result</pre><p><strong>Fix</strong></p><pre>   ValueTask&lt;int&gt; valueTask = GetNumberAsync();<br>   int result = await valueTask; // Always await or handle the result</pre><p><strong>4. ValueTask Struggles in Long-Lived Objects</strong></p><p>ValueTask<strong> </strong>is a value type (struct), and it does not manage its own state. It directly references the underlying operation or resource. If the resource (e.g., DbContext) is disposed, the ValueTask becomes invalid.</p><p>However a Task is a reference type that encapsulates the state of the asynchronous operation. Once a Taskis created, it is independent of the method or object that created it.</p><p>If DbContextis disposed, the Taskwill still throw an exception, but the Taskitself remains valid and can be awaited safely.</p><p>See “<strong>Example 2: Using ValueTask in a Repository</strong>” above where we await ToListAsync() inside the repository method to avoid potential DbContext disposal before the result is consumed. We are awaiting the database call immediately inside the same method instead of leaving the responsibility on the calling function to limit the possibility of disposal. For a Taskas well we would have had the same risk but managing the exception arising due to such a scenario would have been more graceful. I shall try and add some example code for demonstarting this point in the next update.</p><h3>Best Practices for Beginners</h3><p>1. <strong>Start with Task:</strong></p><p>If you’re new to asynchronous programming, stick with Taskfor simplicity.</p><p>Use ValueTaskonly when you understand its trade-offs and need to optimize performance.</p><p>2. <strong>Avoid Multiple Awaiting of ValueTask:</strong></p><p>A ValueTaskshould only be awaited once. If you need to await it multiple times, convert it to a Taskusing .AsTask().</p><p>3. <strong>Use async for Complex Methods:</strong></p><p>It improves readability and exception handling in methods with multiple awaits.</p><p>4.<strong> Handle Exceptions Properly:</strong></p><p>When returning Task/ValueTask without async, remember that exceptions must be explicitly handled.</p><h3>Conclusion</h3><p>ValueTask is a powerful optimization tool in asynchronous C# programming, but it comes with added complexity and usage caveats. For most scenarios, Task remains the preferred choice for its simplicity and reliability. Use ValueTask judiciously—only when performance is critical and the result is frequently synchronous.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b92126ad9c1d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/c-snaps-sharp-bites-for-better-code/a-beginners-guide-to-valuetask-and-task-in-c-b92126ad9c1d">A Beginner’s Guide to ValueTask and Task in C#</a> was originally published in <a href="https://medium.com/c-snaps-sharp-bites-for-better-code">C# Snaps: Sharp Bites for Better Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>