<?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[Stories by sharmila subbiah on Medium]]></title>
        <description><![CDATA[Stories by sharmila subbiah on Medium]]></description>
        <link>https://medium.com/@malarsharmila?source=rss-f55eee0c1eaa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*h8zHH9mnZiuEva10.jpg</url>
            <title>Stories by sharmila subbiah on Medium</title>
            <link>https://medium.com/@malarsharmila?source=rss-f55eee0c1eaa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 20:45:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@malarsharmila/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Build a Conversational AI Chatbot in C# That Remembers Context (OpenAI SDK 2.0)]]></title>
            <link>https://medium.com/@malarsharmila/build-a-conversational-ai-chatbot-in-c-that-remembers-context-openai-sdk-2-0-9eddfb7e475f?source=rss-f55eee0c1eaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/9eddfb7e475f</guid>
            <dc:creator><![CDATA[sharmila subbiah]]></dc:creator>
            <pubDate>Thu, 06 Nov 2025 15:54:53 GMT</pubDate>
            <atom:updated>2025-11-06T15:54:53.329Z</atom:updated>
            <content:encoded><![CDATA[<p>Large Language Models (LLMs) like GPT-4 have transformed how developers can build AI-powered applications. If you’re a C# developer curious about integrating OpenAI into your apps, this guide is for you.We’ll walk through building a <strong>simple AI chat console app in C#</strong>.</p><h4>Step 1: Set Up Your Project</h4><p>First, create a new C# console project using the .NET CLI:</p><pre>dotnet new console -n LLMChatDemo<br>cd LLMChatDemo</pre><p>Next, install the official OpenAI SDK:</p><pre>dotnet add package OpenAI --version 2.0.0</pre><h4>Step 2: Set Your OpenAI API Key</h4><p>The SDK needs an API key to authenticate with OpenAI:</p><ol><li>Go to <a href="https://platform.openai.com/">OpenAI Platform</a> and generate an API key</li><li>Set it as an environment variable</li></ol><pre># Windows (Command Prompt)<br>setx OPENAI_API_KEY &quot;your-api-key-here&quot;<br><br># Windows (PowerShell)<br>$env:OPENAI_API_KEY=&quot;your-api-key-here&quot;<br><br># macOS/Linux<br>export OPENAI_API_KEY=&quot;your-api-key-here&quot;</pre><h4>Step 3: Write the Chat App</h4><p>Here’s a minimal working version compatible with OpenAI SDK 2.0.0:</p><pre>using System;<br>using System.Collections.Generic;<br>using System.Threading.Tasks;<br>using OpenAI.Chat;<br><br>class Program<br>{<br>    static async Task Main()<br>    {<br>        string apiKey = Environment.GetEnvironmentVariable(&quot;OPENAI_API_KEY&quot;);<br>        if (string.IsNullOrWhiteSpace(apiKey))<br>        {<br>            Console.WriteLine(&quot;Error: Set your OPENAI_API_KEY environment variable first!&quot;);<br>            Console.WriteLine(&quot;Restart your terminal after setting it.&quot;);<br>            return;<br>        }<br><br>        // Initialize the OpenAI Chat client<br>        var client = new ChatClient(&quot;gpt-4o-mini&quot;, apiKey);<br>        <br>        // Maintain conversation history<br>        var messages = new List&lt;ChatMessage&gt;<br>        {<br>            new SystemChatMessage(&quot;You are a helpful assistant.&quot;)<br>        };<br><br>        Console.WriteLine(&quot;Welcome to your first LLM chat! Type &#39;exit&#39; to quit.\n&quot;);<br><br>        while (true)<br>        {<br>            Console.Write(&quot;You: &quot;);<br>            var userInput = Console.ReadLine();<br>            <br>            if (string.IsNullOrWhiteSpace(userInput) || userInput.ToLower() == &quot;exit&quot;)<br>                break;<br><br>            // Add user message to history<br>            messages.Add(new UserChatMessage(userInput));<br><br>            try<br>            {<br>                // Send request to OpenAI<br>                var completion = await client.CompleteChatAsync(messages);<br>                var assistantMessage = completion.Value.Content[0].Text;<br><br>                // Add assistant response to history<br>                messages.Add(new AssistantChatMessage(assistantMessage));<br><br>                Console.WriteLine($&quot;\nAssistant: {assistantMessage}\n&quot;);<br>            }<br>            catch (Exception ex)<br>            {<br>                Console.WriteLine($&quot;\nError: {ex.Message}\n&quot;);<br>            }<br>        }<br><br>        Console.WriteLine(&quot;Goodbye!&quot;);<br>    }<br>}</pre><p>How It Works<br>1. SDK Initialization: We create a ChatClient with the model name and API key<br>2. Conversation History: We maintain a list of ChatMessage objects so the AI remembers the conversation context<br>3. Message Loop:<br> • User input is added as a UserChatMessage<br> • The entire history is sent to OpenAI<br> • The response is extracted and displayed<br> • The assistant’s response is added to history for context in future messages</p><h4>Step 4: Run Your App</h4><pre>dotnet run</pre><p>You should see:</p><pre>Welcome to your first LLM chat! Type &#39;exit&#39; to quit.<br><br>You: hey</pre><p>This is just the beginning , from adding chat history to integrating a GUI, the possibilities are endless. Start experimenting and see what your AI chat app can do!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9eddfb7e475f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tell, Don’t Ask: The Principle That Makes Code Behave Better]]></title>
            <link>https://medium.com/c-sharp-programming/tell-dont-ask-the-principle-that-makes-code-behave-better-f07333e2799b?source=rss-f55eee0c1eaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/f07333e2799b</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[sharmila subbiah]]></dc:creator>
            <pubDate>Wed, 04 Jun 2025 16:08:26 GMT</pubDate>
            <atom:updated>2025-06-04T16:08:26.040Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F49tX-yDJINGcP7QXkqCsg.png" /><figcaption>AI Generated</figcaption></figure><p>There’s a subtle but powerful principle in object-oriented programming that can make our code lot cleaner, smarter, and a lot easier to work with:<strong><em>Tell, Don’t Ask</em></strong></p><h4>What Does “Tell, Don’t Ask” Actually Mean?</h4><p>Imagine we’re working with an Order object — a pretty common scenario. Here’s how we might handle a bit of business logic:</p><pre>if (order.Status == OrderStatus.Pending)<br>{<br>    order.Status = OrderStatus.Approved;<br>    order.ApprovedAt = DateTime.UtcNow;<br>}</pre><p>Seems harmless enough, right?</p><p>But under the surface, we’re quietly breaking one of the core rules of good object-oriented design.</p><p>Here’s what’s really happening:</p><ul><li>You’re <strong>asking</strong> the object for its internal state</li><li>Then you’re making decisions <strong>outside</strong> the object</li><li>And you’re <strong>manually setting its properties</strong> from the outside.</li></ul><p>We’re treating Order like a simple data container — not a true domain object with real responsibility. And that’s how we end up with classes that <em>look</em> like objects but don’t actually <em>do</em> anything meaningful.</p><h4>Telling Objects What to Do</h4><p>Let’s flip the approach and <strong>tell</strong> the object what needs to happen:</p><pre>order.Approve();</pre><p>Here’s how the Order class might be implemented:</p><pre>public class Order<br>{<br>    public OrderStatus Status { get; private set; }<br>    public DateTime? ApprovedAt { get; private set; }<br><br>    public void Approve()<br>    {<br>        if (Status != OrderStatus.Pending)<br>            throw new InvalidOperationException(&quot;Only pending orders can be approved.&quot;);<br><br>        Status = OrderStatus.Approved;<br>        ApprovedAt = DateTime.UtcNow;<br>    }<br>}</pre><p>Now the Order is doing exactly what it was designed to do.</p><ul><li>It <strong>protects its own rules</strong> — only pending orders can be approved, and that’s enforced inside the object.</li><li>The logic is <strong>centralized</strong> — we don’t have scattered if (status == X) logic all over the codebase</li><li>And code is now <strong>communicating intent</strong>, not mechanics. It’s easy to read, and hard to misuse.</li></ul><h4>Final Thoughts</h4><p>In C# — especially when we’re modeling real business logic or using domain-driven design — “Tell, Don’t Ask” helps us write better code.</p><p>It encourages code that:</p><ul><li><strong>Reads like a story</strong>, not like a set of instructions</li><li><strong>Keeps objects in charge of themselves</strong>, which leads to fewer bugs</li><li><strong>Gives models real behavior</strong>, not just fields with names</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f07333e2799b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/c-sharp-programming/tell-dont-ask-the-principle-that-makes-code-behave-better-f07333e2799b">Tell, Don’t Ask: The Principle That Makes Code Behave Better</a> was originally published in <a href="https://medium.com/c-sharp-programming">Any Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Exploring Null-Conditional Assignment in .NET 10 Preview]]></title>
            <link>https://medium.com/c-sharp-programming/exploring-null-conditional-assignment-in-net-10-preview-ee4059296649?source=rss-f55eee0c1eaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee4059296649</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[csharp-programming]]></category>
            <category><![CDATA[dotnet-10]]></category>
            <dc:creator><![CDATA[sharmila subbiah]]></dc:creator>
            <pubDate>Mon, 14 Apr 2025 15:47:48 GMT</pubDate>
            <atom:updated>2025-04-21T19:18:57.022Z</atom:updated>
            <content:encoded><![CDATA[<h3>🌟 Exploring Null-Conditional Assignment in .NET 10 Preview</h3><p>.NET 10 preview 1 introduces a neat new feature that many developers will appreciate: <strong>null-conditional assignment</strong>. This small but powerful addition can help clean up your code and make null checks more concise and expressive.</p><h4>🔍 Consider This Familiar Pattern</h4><pre>public class Customer<br>{<br>    public string Name { get; set; }<br>    public int Age { get; set; }<br>}<br><br>public class UpdateCustomer<br>{<br>    public static void UpdateAge(Customer? customer, int newAge)<br>    {<br>        if (customer is not null)<br>        {<br>            customer.Age = newAge;<br>        }<br>    }<br>}</pre><p>Here, we’re checking if customer is not null before assigning a value to Age. It’s safe, but a bit verbose—especially when you do this kind of check often.</p><h4>✅ The New Way: Null-Conditional Assignment</h4><p>.NET 10 lets us to simplify that logic with a new syntax:</p><pre>public static void UpdateAge(Customer? customer, int newAge)<br>{<br>    customer?.Age = newAge;<br>}</pre><p>If customer is null, the assignment is skipped. If it’s not null, Age gets updated. Just like the traditional null check, but cleaner.</p><p>This gets even more powerful when we deal with <strong>nested objects</strong> — the kind you’d normally protect with a long chain of null checks. Now, We can write something like this:</p><pre>nestedObj? o = blah();<br>o?.x?.y = &quot;Duh&quot;;</pre><h4>🔗 References and Community Discussion</h4><p>Want to dive deeper into this feature?</p><ul><li>📘 <a href="https://github.com/dotnet/core/blob/main/release-notes/10.0/preview/preview3/csharp.md#null-conditional-assignment">.NET 10 Preview 3 release notes on GitHub</a></li><li>💬 <a href="https://github.com/dotnet/csharplang/discussions/8676">C# Language Design Discussion #8676 — Null-conditional assignment proposal</a></li></ul><p>These links provide technical background, examples, and insight into how and why this feature was introduced.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee4059296649" width="1" height="1" alt=""><hr><p><a href="https://medium.com/c-sharp-programming/exploring-null-conditional-assignment-in-net-10-preview-ee4059296649">🌟 Exploring Null-Conditional Assignment in .NET 10 Preview</a> was originally published in <a href="https://medium.com/c-sharp-programming">Any Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Developer’s Guide to Diagrams]]></title>
            <link>https://medium.com/c-sharp-programming/a-developers-guide-to-diagrams-f87766bed627?source=rss-f55eee0c1eaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/f87766bed627</guid>
            <category><![CDATA[documentation]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[sharmila subbiah]]></dc:creator>
            <pubDate>Thu, 03 Apr 2025 16:04:01 GMT</pubDate>
            <atom:updated>2025-04-03T16:04:01.209Z</atom:updated>
            <content:encoded><![CDATA[<p>Not every diagram type in your toolset is worth your time — but some are absolute game-changers for clarity, collaboration, and scalability.</p><h4>1. Architecture Diagrams</h4><blockquote><strong><em>Use for:</em></strong><em> High-level system design, services, data flow, infrastructure</em></blockquote><p>Architecture diagrams help visualize how different components or services fit together in a system. Whether it’s microservices, cloud infrastructure, or third-party integrations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*kZYAFi1cXPfZVSHwzifwlA.png" /></figure><h4>2. Sequence Diagrams</h4><blockquote><strong><em>Use for:</em></strong><em> Showing how components interact </em>over time</blockquote><p>These are perfect for modeling request flows, service calls, or async processes. They help answer:<br> <em>“What happens first?”</em><br> <em>“Who calls whom?”</em></p><p>Sequence diagrams are a great way to document APIs, service orchestration, or complex business logic timelines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*X8Ep1Be_VF6LBsX9mmovxA.png" /></figure><h4>3. ER Diagrams (Entity-Relationship)</h4><blockquote><strong><em>Use for:</em></strong><em> Designing and visualizing </em><strong><em>relational database schemas</em></strong></blockquote><p>ER diagrams describe:</p><ul><li><strong>Entities</strong> (tables)</li><li><strong>Attributes</strong> (fields/columns)</li><li><strong>Relationships</strong> (1:1, 1:N, N:M)</li></ul><p>They’re essential when designing or updating databases — whether you’re working solo or collaborating with backend/data teams.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*UTVDOKc8OsMO2NVBcjePEA.png" /></figure><h4>4. Flowcharts / Logic Diagrams</h4><blockquote><strong><em>Use for:</em></strong><em> Mapping out </em><strong><em>business logic, decision trees, or condition-based flows</em></strong></blockquote><p>From form validations to payment workflows, flowcharts make it easy to understand conditional logic and branching paths.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/1*0NrJoCdXDiiVuKKrEBDw8A.png" /></figure><h4>5. UML Class Diagrams</h4><blockquote><strong><em>Use for:</em></strong><em> Modeling </em><strong><em>object-oriented structures</em></strong></blockquote><p>UML Class diagrams show:</p><ul><li>Classes and their attributes/methods</li><li>Relationships like inheritance, aggregation, and associations</li></ul><p>Ideal for designing or reverse-engineering OOP systems. Helps clarify structure before writing a single line of code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*0iVfbr9Jfa8zcdlrB7GQ2A.png" /></figure><h4>‍6. Swimlane Diagrams</h4><blockquote><strong><em>Use for:</em></strong><em> Visualizing </em><strong><em>who does what</em></strong><em> in a multi-role or multi-team process</em></blockquote><p>Each lane represents a role or team. The diagram tracks actions horizontally or vertically — making it super clear where handoffs happen in a process (like order fulfillment, onboarding, or support flows).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oMU-LdYWSbMhfYOWgXfnsQ.png" /></figure><h4>Final Thoughts</h4><p>You don’t need to learn <strong>every</strong> diagram type — just the ones that give you the most value for the problems you’re solving. These 6 will cover <strong>90% of what you’ll need as a developer</strong>, from architecture to business logic to team workflows</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f87766bed627" width="1" height="1" alt=""><hr><p><a href="https://medium.com/c-sharp-programming/a-developers-guide-to-diagrams-f87766bed627">A Developer’s Guide to Diagrams</a> was originally published in <a href="https://medium.com/c-sharp-programming">Any Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Guard vs Validator in C#: Understanding the Right Tool for the Job]]></title>
            <link>https://medium.com/c-sharp-programming/guard-vs-validator-in-c-understanding-the-right-tool-for-the-job-248006155ff0?source=rss-f55eee0c1eaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/248006155ff0</guid>
            <category><![CDATA[csharp-programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[sharmila subbiah]]></dc:creator>
            <pubDate>Thu, 13 Mar 2025 09:47:24 GMT</pubDate>
            <atom:updated>2025-03-13T13:04:36.525Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*GcbYcLge-eX-dsz7.png" /></figure><p>At first glance, they seem to serve the same purpose: making sure invalid data doesn’t make its way into our system. But the way they work, and more importantly, <em>when</em> you use them, are very different.</p><p><strong>Guard Clauses: </strong>Think of Guard clauses as your bouncer at the club. They don’t care about your entire backstory — they just check <strong>one thing</strong> at a time and stop you at the door if you don’t meet the criteria.</p><h4>When to Use Guards</h4><ul><li>When you need to <strong>validate individual method parameters</strong>.</li><li>When invalid input should <strong>immediately trigger an exception</strong>.</li><li>When writing <strong>defensive programming</strong> — ensuring methods aren’t even entered if parameters are bad.</li></ul><p>A Simple Guard Implementation: Let’s say we have a method that processes a payment, and we want to make sure:</p><ol><li>The amount isn’t negative.</li><li>The customerId isn’t null or empty.</li></ol><pre>  public static class Guard<br>  {<br>      public static void AgainstNullOrEmpty(string value, string paramName)<br>      {<br>          if (string.IsNullOrEmpty(value))<br>          {<br>              throw new ArgumentException($&quot;Parameter {paramName} cannot be null or empty.&quot;);<br>          }<br>      }<br><br>      public static void AgainstNegative(decimal value, string paramName)<br>      {<br>          if (value &lt; 0)<br>          {<br>              throw new ArgumentOutOfRangeException(paramName, &quot;Value cannot be negative.&quot;);<br>          }<br>      }<br>  }</pre><p>Now, we use this in our ProcessPayment method:</p><pre>void ProcessPayment(string customerId, decimal amount)<br>{<br>    Guard.AgainstNullOrEmpty(customerId, nameof(customerId));<br>    Guard.AgainstNegative(amount, nameof(amount));<br><br>    Console.WriteLine($&quot;Processing payment of ${amount} for customer {customerId}.&quot;);<br>}</pre><h4>What Happens Here?</h4><ul><li>If customerId is null or empty → we immediately <strong>throw an exception</strong>.</li><li>If amount is negative → we <strong>throw an exception</strong>.</li><li>If both are valid → we continue with payment processing.</li></ul><p><strong>Guard clauses are great because they make the code cleaner and prevent us from nesting </strong><strong>if statements deep inside the method.</strong></p><p><strong>Validators: </strong>Let’s say we’re processing an Order instead of a single value.</p><ul><li>An <strong>Order</strong> might have multiple fields that need validation.</li><li>Some fields might need <strong>cross-checking.</strong></li><li>Instead of throwing exceptions, we might want to <strong>collect all errors</strong> and return them. This is where a <strong>Validator</strong> comes in.</li></ul><p>When to Use a Validator</p><ul><li>When you’re validating <strong>entire objects</strong>.</li><li>When multiple rules must be checked together.</li><li>When you want to <strong>return</strong> validation results instead of immediately throwing exceptions.</li></ul><p>A Simple Validator:</p><pre>public class OrderValidator<br>{<br>    public List&lt;string&gt; Validate(Order order)<br>    {<br>        var errors = new List&lt;string&gt;();<br><br>        if (order.Quantity &lt;= 0)<br>        {<br>            errors.Add(&quot;Quantity must be greater than zero.&quot;);<br>        }<br><br>        if (string.IsNullOrEmpty(order.CustomerName))<br>        {<br>            errors.Add(&quot;Customer name is required.&quot;);<br>        }<br><br>        if (order.TotalAmount &lt; 10)<br>        {<br>            errors.Add(&quot;Total amount must be at least $10.&quot;);<br>        }<br><br>        return errors;<br>    }<br>}</pre><p>Now, we use it when processing an order:</p><pre>var order = new Order { Quantity = -5, CustomerName = &quot;&quot;, TotalAmount = 5 };<br>var validator = new OrderValidator();<br>var errors = validator.Validate(order);<br><br>if (errors.Any())<br>{<br>    Console.WriteLine(&quot;Validation failed: &quot; + string.Join(&quot;, &quot;, errors));<br>}</pre><h4>What Happens Here?</h4><ul><li>Instead of stopping immediately like a Guard, the validator <strong>collects all validation issues</strong>.</li><li>It returns a <strong>list of errors</strong>, which we can then log, display to the user, or handle appropriately.</li></ul><p><strong>Validators are great because they work at an object level and allow flexible error handling.</strong></p><h4>Final Thoughts</h4><p>Both <strong>Guard clauses</strong> and <strong>Validators</strong> are critical tools in a C# developer’s toolkit, but they serve <strong>different purposes</strong>:</p><ul><li><strong>Use Guards when preventing invalid input at the method level.</strong></li><li><strong>Use Validators when working with objects and returning structured validation results.</strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=248006155ff0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/c-sharp-programming/guard-vs-validator-in-c-understanding-the-right-tool-for-the-job-248006155ff0">Guard vs Validator in C#: Understanding the Right Tool for the Job</a> was originally published in <a href="https://medium.com/c-sharp-programming">Any Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Random.Next() in C#: Generating Random Numbers Efficiently]]></title>
            <link>https://medium.com/c-sharp-programming/understanding-random-next-in-c-generating-random-numbers-efficiently-67aaa69bf4fd?source=rss-f55eee0c1eaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/67aaa69bf4fd</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[csharp-programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[sharmila subbiah]]></dc:creator>
            <pubDate>Mon, 10 Feb 2025 10:11:05 GMT</pubDate>
            <atom:updated>2025-02-10T17:45:08.410Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*U-M1EI0jm82cstRSvhuBTw.png" /><figcaption>AI Generated</figcaption></figure><h4><strong>Introduction</strong></h4><p>Generating random numbers is a common requirement in software development, whether for simulations, games, cryptography, or testing. In C#, the Random class provides an easy way to generate pseudo-random numbers, with Random.Next() being one of its most commonly used methods.</p><p>This article explores the proper use of Random.Next(), common mistakes, and best practices for generating random numbers efficiently.</p><h4>Basics of Random.Next()</h4><p>The Random.Next() method is part of the System namespace and provides different overloads for generating random integers. Each time Next() is called, it returns a new pseudo-random number within the specified range.</p><pre><br>Random random = new Random();<br><br>Console.WriteLine(random.Next()); //Next() Returns a non-negative random integer.<br>Console.WriteLine(random.Next(100));  //Next(int maxValue) Returns a non-negative random integer less than maxValue.<br>Console.WriteLine(random.Next(50, 100));  //Next(int minValue, int maxValue) Returns a random integer in the range [minValue, maxValue).</pre><h4>How Seeding Affects Randomness</h4><p>The Random class uses a seed value to generate random numbers. If you create multiple instances with the same seed, they will produce identical sequences of numbers:</p><pre>Random random1 = new Random(42);<br>Random random2 = new Random(42);<br><br>Console.WriteLine(random1.Next(100)); // Always the same result<br>Console.WriteLine(random2.Next(100)); // Always the same result<br>//This is useful for testing and debugging, but in most cases, we want truly random values.</pre><h4>Common Mistakes with Random and How to Fix Them</h4><p>❌ Creating Multiple Random Instances in a Loop</p><p>Instantiating Random multiple times in a short time frame can lead to duplicate values because the instances may be seeded with the same timestamp.</p><pre>for (int i = 0; i &lt; 5; i++)<br>{<br>    Random rand = new Random();<br>    Console.WriteLine(rand.Next(100));<br>}<br><br>// Solution: Use a Single Random Instance<br><br>Random rand = new Random();<br><br>for (int i = 0; i &lt; 5; i++)<br>{<br>    Console.WriteLine(rand.Next(100));<br>}<br></pre><p>❌ Incorrect Multi-Threading Usage</p><p>The Random class is <strong>not thread-safe</strong>, meaning concurrent access can lead to duplicate values or unexpected behavior</p><pre>Parallel.For(0, 5, i =&gt;<br>{<br>    Random rand = new Random();<br>    Console.WriteLine(rand.Next(100));<br>}); <br>// Each thread creates a separate Random instance, often leading to the same values.<br><br> // Solution 1: Use ThreadLocal&lt;Random&gt;<br><br>class Program<br>{<br>    private static ThreadLocal&lt;Random&gt; random = new ThreadLocal&lt;Random&gt;(() =&gt; new Random());<br><br>    static void Main()<br>    {<br>        Parallel.For(0, 5, i =&gt;<br>        {<br>            Console.WriteLine(random.Value.Next(100));<br>        });<br>    }<br>}<br><br>//  Solution 2: Use Random.Shared<br>for (int i = 0; i &lt; 5; i++)<br>{<br>    Console.WriteLine(Random.Shared.Next(100));<br>}</pre><h4>Generating Random Floating-Point Numbers</h4><p>Random.Next() only generates integers, but you can generate random floating-point numbers using Random.NextDouble():</p><pre>double randomDouble = new Random().NextDouble(); // Range: 0.0 to 1.0<br>Console.WriteLine(randomDouble);<br><br>// To generate floating-point numbers in a specific range:<br>double min = 5.0, max = 10.0;<br>double randomInRange = min + (max - min) * new Random().NextDouble();<br>Console.WriteLine(randomInRange); // Between 5.0 and 10.0</pre><h4>Generating Secure Random Numbers</h4><p>For cryptographic security (e.g., generating tokens, passwords), Random is not secure. Instead, use RandomNumberGenerator from System.Security.Cryptography:</p><pre>using System;<br>using System.Security.Cryptography;<br><br>class Program<br>{<br>    static void Main()<br>    {<br>        byte[] buffer = new byte[4];<br>        RandomNumberGenerator.Fill(buffer);<br>        int secureRandom = BitConverter.ToInt32(buffer, 0) &amp; int.MaxValue;<br><br>        Console.WriteLine(secureRandom);<br>    }<br>}<br>// This ensures truly unpredictable numbers, unlike Random.</pre><p>Unlike Random, RandomNumberGenerator provides cryptographically secure random numbers, ensuring they are <strong>unpredictable and suitable for security-sensitive applications</strong>.</p><h4>Best Practices for Using Random.Next()</h4><p>✔ <strong>Use a single </strong><strong>Random instance</strong> instead of creating multiple instances in a loop.<br>✔ <strong>Use </strong><strong>Random.Shared</strong> for thread-safe random number generation (C# 9+).<br>✔ <strong>Use </strong><strong>ThreadLocal&lt;Random&gt;</strong> for multi-threaded applications in older versions.<br>✔ <strong>Use </strong><strong>RandomNumberGenerator</strong> for security-sensitive scenarios.</p><h4>Conclusion</h4><p>The Random.Next() method is a powerful and commonly used tool for generating random numbers in C#. However, <strong>proper usage is crucial</strong> to avoid common pitfalls such as re-initialization issues, multi-threading conflicts, and insecure randomness. By following best practices, you can generate <strong>efficient, reliable, and secure</strong> random numbers in your applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67aaa69bf4fd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/c-sharp-programming/understanding-random-next-in-c-generating-random-numbers-efficiently-67aaa69bf4fd">Understanding Random.Next() in C#: Generating Random Numbers Efficiently</a> was originally published in <a href="https://medium.com/c-sharp-programming">Any Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Functional Programming in C#: Action and Func]]></title>
            <link>https://medium.com/c-sharp-programming/functional-programming-in-c-action-and-func-53bfe56a8da3?source=rss-f55eee0c1eaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/53bfe56a8da3</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[sharmila subbiah]]></dc:creator>
            <pubDate>Tue, 21 Jan 2025 09:23:12 GMT</pubDate>
            <atom:updated>2025-01-29T16:29:16.005Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v7uSa0vwvbDCZFq_WFr5sQ.png" /></figure><p>Action and Func are essential delegates in C# that simplify functional programming by providing predefined templates for method handling. They eliminate the need for custom delegates, making code cleaner, reusable, and expressive.</p><h4>1. What Are Action and Func Delegates?</h4><p><strong>Delegates in C#: A Quick Recap</strong></p><p>A delegate is a type-safe pointer to a method, enabling you to pass methods as parameters, store them in variables, or return them from functions. Traditionally, custom delegates require explicit definitions, but Action and Func streamline this process with predefined templates.</p><p><strong>Key Differences Between </strong><strong>Action and </strong><strong>Func</strong></p><ul><li><strong>Action</strong>: Represents a method with zero or more input parameters and <strong>no return value</strong> (void).</li><li><strong>Func</strong>: Represents a method with zero or more input parameters and a <strong>return value</strong>. The <strong>last generic parameter</strong> specifies the return type.</li></ul><h4>Why Use Action and Func?</h4><p><strong>Benefits in Modern C# Programming:</strong></p><ol><li><strong>Code Reusability</strong>: Pass methods as parameters to other methods.</li><li><strong>Simplified Event Handling</strong>: Streamline callbacks and event-driven logic.</li><li><strong>LINQ Support</strong>: Enable functional operations like filtering (Where) and transformations (Select).</li><li><strong>Dynamic Pipelines</strong>: Compose methods at runtime.</li></ol><h4>Practical Examples</h4><pre>// Using Action<br>Action&lt;string&gt; greet = name =&gt; Console.WriteLine($&quot;Hello, {name}!&quot;);<br>greet(&quot;Alice&quot;); // Output: Hello, Alice!<br><br>// Using Func<br>Func&lt;int, int, int&gt; add = (a, b) =&gt; a + b;<br>int sum = add(5, 10); // Returns 15<br>Console.WriteLine(sum); // Output: 15<br><br><br>//Use Action when no return value is required.<br>Action&lt;string&gt; log = message =&gt; Console.WriteLine($&quot;Log: {message}&quot;);<br>log(&quot;Operation completed.&quot;); // Output: Log: Operation completed.<br><br>//Use Func for data transformations.<br>Func&lt;int, string&gt; numberToString = number =&gt; $&quot;Number: {number}&quot;;<br>string result = numberToString(42); // Returns &quot;Number: 42&quot;<br>Console.WriteLine(result);<br><br>//Chain multiple Action delegates.<br>Action&lt;string&gt; print = Console.WriteLine;<br>Action&lt;string&gt; exclaim = s =&gt; Console.WriteLine($&quot;{s}!&quot;);<br>Action&lt;string&gt; combined = print + exclaim;<br><br>combined(&quot;Hello&quot;); // Output: Hello Hello!<br><br>//Enhance LINQ queries with Func.<br><br>var numbers = new List&lt;int&gt; { 1, 2, 3, 4, 5 };<br>var evenNumbers = numbers.Where(n =&gt; n % 2 == 0).ToList();<br><br>evenNumbers.ForEach(n =&gt; Console.WriteLine(n)); // Output: 2 4<br></pre><h4>Common Pitfalls and Best Practices</h4><p>1.Avoid using large lambdas that reduce readability.</p><pre>//Avoid<br>Action&lt;int&gt; print = x =&gt; {<br>    if (x % 2 == 0) Console.WriteLine($&quot;{x} is even&quot;);<br>    else Console.WriteLine($&quot;{x} is odd&quot;);<br>};<br><br>//Use Named Methods Instead:<br>void PrintEvenOdd(int x) {<br>    Console.WriteLine(x % 2 == 0 ? $&quot;{x} is even&quot; : $&quot;{x} is odd&quot;);<br>}<br>Action&lt;int&gt; print = PrintEvenOdd;<br>print(5); // Output: 5 is odd</pre><p>2.Avoid using variable Capturing in Loops</p><pre>//Avoid:<br>List&lt;Action&gt; actions = new List&lt;Action&gt;();<br>for (int i = 0; i &lt; 3; i++) {<br>    actions.Add(() =&gt; Console.WriteLine(i)); // Prints 3, 3, 3<br>}<br>actions.ForEach(action =&gt; action());<br><br>//Solution:<br>for (int i = 0; i &lt; 3; i++) {<br>    int localI = i;<br>    actions.Add(() =&gt; Console.WriteLine(localI)); // Prints 0, 1, 2<br>}<br>actions.ForEach(action =&gt; action());</pre><h3>Conclusion</h3><p>Action and Func empower developers to embrace functional programming principles in C#, enhancing code clarity, reusability, and modularity. Whether you&#39;re working with event-driven code, LINQ queries, or dynamic pipelines, these delegates simplify method handling while reducing boilerplate code. By understanding their capabilities and avoiding common pitfalls, you can elevate your C# programming and write cleaner, more efficient code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53bfe56a8da3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/c-sharp-programming/functional-programming-in-c-action-and-func-53bfe56a8da3">Functional Programming in C#: Action and Func</a> was originally published in <a href="https://medium.com/c-sharp-programming">Any Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debug Smarter with Debug.Assert and Trace.Assert:]]></title>
            <link>https://medium.com/c-sharp-programming/debug-smarter-with-debug-assert-and-trace-assert-36dcbb835053?source=rss-f55eee0c1eaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/36dcbb835053</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[csharp-programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[sharmila subbiah]]></dc:creator>
            <pubDate>Tue, 07 Jan 2025 09:15:11 GMT</pubDate>
            <atom:updated>2025-01-07T09:15:11.486Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*6KZC6X9stFvijhjBASXH8Q.png" /><figcaption>AI Generated</figcaption></figure><p>Debugging and validation are cornerstones of reliable software development. They ensure that code behaves as expected under all scenarios, helping to identify and fix issues early in the development process. By proactively validating assumptions, developers can prevent subtle bugs from evolving into costly errors during production.</p><h4>What Are Debug.Assert and Trace.Assert?</h4><h4>Debug.Assert</h4><p>Debug.Assert verifies conditions during development. These assertions are only evaluated in <strong>Debug</strong> builds, allowing developers to check for issues without impacting the performance of Release builds.</p><h4>Trace.Assert</h4><p>Trace.Assert validates conditions in both <strong>Debug</strong> and <strong>Release</strong> builds if tracing is enabled. This makes it suitable for monitoring critical runtime conditions in production-like environments.</p><h4>Key Differences Between Debug.Assert and Trace.Assert</h4><ul><li>Behavior in build configurations.</li><li>Use cases for debugging versus runtime tracing.</li></ul><h4>Syntax and Usage</h4><p>Basic syntax for both assertions:</p><pre>Debug.Assert(condition, &quot;Message if condition is false&quot;);<br>Trace.Assert(condition, &quot;Message if condition is false&quot;);</pre><h4><strong>Example: Debug.Assert</strong></h4><p>The following example uses Debug.Assert to validate a method&#39;s precondition:</p><pre>using System.Diagnostics;<br><br>public class AccountManager<br>{<br>    public void Withdraw(decimal amount, decimal balance)<br>    {<br>        // Precondition: The amount must not exceed the balance<br>        Debug.Assert(amount &lt;= balance, &quot;Withdrawal amount exceeds balance.&quot;);<br><br>        balance -= amount;<br>        Console.WriteLine($&quot;Withdrawal successful. Remaining balance: {balance}&quot;);<br>    }<br>}<br><br>public class Program<br>{<br>    public static void Main()<br>    {<br>        AccountManager manager = new();<br><br>        decimal balance = 100m;<br>        manager.Withdraw(150m, balance); // This will trigger the assertion<br>    }<br>}<br><br>// outputs - Assertion Failed: Withdrawal amount exceeds balance.</pre><h4>Example: Trace.Assert</h4><p>Trace.Assert is useful in scenarios where monitoring is required in both Debug and Release builds:</p><pre>using System.Diagnostics;<br><br>public class ServiceMonitor<br>{<br>    public void MonitorService(string serviceStatus)<br>    {<br>        // Ensure the service status is &quot;Running&quot;<br>        Trace.Assert(serviceStatus == &quot;Running&quot;, &quot;Service is not running.&quot;);<br><br>        if (serviceStatus == &quot;Running&quot;)<br>        {<br>            Console.WriteLine(&quot;Service is operational.&quot;);<br>        }<br>    }<br>}<br><br>public class Program<br>{<br>    public static void Main()<br>    {<br>        Trace.Listeners.Add(new TextWriterTraceListener(&quot;log.txt&quot;));<br>        Trace.AutoFlush = true;<br><br>        ServiceMonitor monitor = new();<br>        monitor.MonitorService(&quot;Stopped&quot;); // Logs an assertion failure<br>    }<br>}</pre><p>In this example, an assertion failure is logged to log.txt in both Debug and Release builds if the service status is not &quot;Running.&quot;</p><h4>When to Use Assertions:</h4><p><strong>Invariants</strong>: Confirm that internal state remains consistent during execution.</p><pre>Debug.Assert(dictionary != null &amp;&amp; dictionary.Count &gt; 0, &quot;Dictionary is empty or null.&quot;);</pre><p><strong>Preconditions</strong>: Validate inputs at the start of a method or function.</p><pre>Debug.Assert(input != null, &quot;Input must not be null.&quot;);</pre><p><strong>Postconditions</strong>: Check the outcomes of a method or process.</p><pre>Debug.Assert(result &gt; 0, &quot;Result must be positive.&quot;);</pre><p><strong>Critical checks in production-like scenarios</strong>: Use Trace.Assert to monitor conditions vital for the application’s operation.</p><h4>When Not to Use Assertions:</h4><p>Avoid replacing exception handling with assertions. Use exceptions for recoverable errors, while assertions are for identifying programmer errors or violations of expectations.</p><pre>// Avoid this<br>Debug.Assert(file.Exists, &quot;File does not exist.&quot;);<br><br>// Use exceptions instead<br>if (!file.Exists)<br>{<br>    throw new FileNotFoundException(&quot;File not found.&quot;);<br>}</pre><p>Assertions should not alter the state of the program or have side effects.</p><pre>Debug.Assert(++counter &gt; 0, &quot;Counter is not positive.&quot;);</pre><h4>Best Practices for Using Assertions:</h4><ul><li>Write meaningful messages to help diagnose issues quickly.</li><li>Use assertions to validate conditions that are critical to the correctness of your program.</li><li>Avoid excessive assertions, which may clutter your code and reduce readability.</li></ul><h3>Conclusions</h3><p>Assertions like Debug.Assert and Trace.Assert are powerful tools for validating assumptions and improving software reliability.</p><ul><li>Use <strong>Debug.Assert</strong> during development to catch logical errors early without impacting Release builds.</li><li>Use <strong>Trace.Assert</strong> to monitor critical conditions in runtime scenarios, leveraging tracing to identify issues in production-like environments.</li></ul><p>By adhering to best practices and using assertions thoughtfully, developers can create more robust and maintainable codebases, ensuring smoother deployments and reduced debugging efforts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36dcbb835053" width="1" height="1" alt=""><hr><p><a href="https://medium.com/c-sharp-programming/debug-smarter-with-debug-assert-and-trace-assert-36dcbb835053">Debug Smarter with Debug.Assert and Trace.Assert:</a> was originally published in <a href="https://medium.com/c-sharp-programming">Any Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Proposal for a LINQ LeftJoin Operator in .NET 10]]></title>
            <link>https://medium.com/c-sharp-programming/proposal-for-a-linq-leftjoin-operator-in-net-10-af74635079a6?source=rss-f55eee0c1eaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/af74635079a6</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[csharp-programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[sharmila subbiah]]></dc:creator>
            <pubDate>Mon, 09 Dec 2024 09:09:44 GMT</pubDate>
            <atom:updated>2024-12-09T09:09:44.764Z</atom:updated>
            <content:encoded><![CDATA[<h3>Proposal for a LINQ LeftJoin Operator in .NET 10</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*5kheIpLA9Tg6Q-exHdDGtw.png" /></figure><p>The proposal for a <strong>LeftJoin operator in .NET 10</strong> brings significant enhancements to LINQ, making left outer joins more accessible and improving code readability. Here&#39;s an overview of how this feature could be shaped and integrated:</p><h4>Purpose and Motivation</h4><ul><li><strong>Current Challenge</strong>: LINQ’s lack of direct support for left outer joins forces developers to use complex constructs (GroupJoin + SelectMany), resulting in verbose and less maintainable code.</li><li><strong>Proposed Solution</strong>: A new LeftJoin operator that aligns with the SQL LEFT JOIN concept, offering a simple, readable way to perform this common operation in .NET.</li></ul><h4>Proposed API Design:</h4><p>The LeftJoin operator would be implemented as an extension method:</p><pre>public static IEnumerable&lt;TResult&gt; LeftJoin&lt;TOuter, TInner, TKey, TResult&gt;(<br>    this IEnumerable&lt;TOuter&gt; outer,<br>    IEnumerable&lt;TInner&gt; inner,<br>    Func&lt;TOuter, TKey&gt; outerKeySelector,<br>    Func&lt;TInner, TKey&gt; innerKeySelector,<br>    Func&lt;TOuter, TInner?, TResult&gt; resultSelector,<br>    IEqualityComparer&lt;TKey&gt;? comparer = null)</pre><p>This method aligns with the existing Join operator but modifies the behavior to include all elements from the outer sequence, pairing them with matching elements from the inner sequence or a default value when no match exists.</p><pre>var customers = new[] { new { Id = 1, Name = &quot;Alice&quot; }, new { Id = 2, Name = &quot;Bob&quot; } };<br>var orders = new[] { new { CustomerId = 2, Order = &quot;Book&quot; } };<br><br>var leftJoin = customers.LeftJoin(<br>    orders,<br>    customer =&gt; customer.Id,<br>    order =&gt; order.CustomerId,<br>    (customer, order) =&gt; new<br>    {<br>        Customer = customer.Name,<br>        Order = order?.Order ?? &quot;No Orders&quot;<br>    });<br></pre><p>The addition of a LeftJoin operator would benefit LINQ providers such as Entity Framework by allowing direct expression of SQL LEFT JOIN operations, which are currently cumbersome to represent.</p><p>This proposal aims to enhance LINQ’s expressiveness and align it more closely with SQL capabilities, simplifying the syntax for left outer joins and improving code readability.</p><blockquote>For more details on the original proposal, refer to the <a href="https://github.com/dotnet/runtime/issues/110292">https://github.com/dotnet/runtime/issues/110292</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af74635079a6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/c-sharp-programming/proposal-for-a-linq-leftjoin-operator-in-net-10-af74635079a6">Proposal for a LINQ LeftJoin Operator in .NET 10</a> was originally published in <a href="https://medium.com/c-sharp-programming">Any Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Feature Switches in .NET 9]]></title>
            <link>https://medium.com/c-sharp-programming/feature-switches-in-net-9-73b1cb96c13f?source=rss-f55eee0c1eaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/73b1cb96c13f</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dotnet-9]]></category>
            <category><![CDATA[csharp-programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[sharmila subbiah]]></dc:creator>
            <pubDate>Wed, 20 Nov 2024 11:11:48 GMT</pubDate>
            <atom:updated>2024-11-20T11:12:50.411Z</atom:updated>
            <content:encoded><![CDATA[<h3>Feature Switches in .NET 9</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*6mpCtPzgdLItCYW0sWsajw.png" /><figcaption>image taken from <a href="https://devblogs.microsoft.com/">https://devblogs.microsoft.com/</a></figcaption></figure><p>In .NET 9, Microsoft introduced a new feature switch mechanism that allows developers to conditionally include or exclude specific functionalities within their applications. This capability is particularly beneficial for optimizing application size and performance, especially when using trimming or Native AOT (Ahead-of-Time) compilation.</p><h4>Understanding Feature Switches</h4><p>Feature switches give developers the ability to toggle features on or off in their applications. When a feature is disabled, the associated code can be excluded during the build process, resulting in a more streamlined and efficient application. This is achieved through two new attributes: FeatureSwitchDefinitionAttribute and FeatureGuardAttribute.</p><h4>FeatureSwitchDefinitionAttribute</h4><p>The FeatureSwitchDefinitionAttribute allows a feature switch property to be treated as a constant during the trimming process. This means that any code guarded by this switch can be removed if the feature is disabled.</p><pre>if (Feature.IsSupported)<br>    Feature.Enable();<br><br>public class Feature<br>{<br>    [FeatureSwitchDefinition(&quot;Feature.IsSupported&quot;)]<br>    internal static bool IsSupported =&gt; AppContext.TryGetSwitch(&quot;Feature.IsSupported&quot;, out bool isEnabled) ? isEnabled : true;<br><br>    internal static void  Enable()<br>    {<br>            Console.WriteLine(&quot;Hello World&quot;);<br>    }<br>}</pre><p>In this example, if Feature.IsSupported is set to false, the Feature.Enable() method will be excluded from the final build, ensuring that unnecessary code is not included.</p><h4>FeatureGuardAttribute</h4><p>The FeatureGuardAttribute designates a feature switch property as a guard for code annotated with attributes like RequiresUnreferencedCodeAttribute, RequiresAssemblyFilesAttribute, or RequiresDynamicCodeAttribute. This ensures that the guarded code is only included if the feature is supported.</p><p>When building with &lt;PublishAot&gt;true&lt;/PublishAot&gt;, the call to Feature.Enable() will not produce analyzer warnings, and the method will be removed during publishing if the feature is not supported.</p><h4>Implementing Feature Switches in Your Project</h4><p>To utilize feature switches, you can define them in your project file (.csproj) as follows:</p><pre>&lt;ItemGroup&gt;<br>    &lt;RuntimeHostConfigurationOption Include=&quot;Feature.IsSupported&quot; Value=&quot;false&quot; Trim=&quot;true&quot; /&gt;<br>&lt;/ItemGroup&gt;</pre><p>Setting the Value to false indicates that the feature is not supported, prompting the trimming process to exclude the associated code.</p><h4>Benefits of Using Feature Switches</h4><p>By leveraging feature switches, developers can:</p><ul><li><strong>Reduce Application Size:</strong> Exclude unnecessary code, leading to smaller binaries.</li><li><strong>Enhance Performance:</strong> Minimize the application’s footprint, resulting in faster load times and improved efficiency.</li><li><strong>Customize Builds:</strong> Tailor the application to include only the necessary features, aligning with specific deployment scenarios.</li></ul><blockquote>For more detailed information, refer to the official Microsoft documentation on <a href="https://learn.microsoft.com/en-us/dotnet/core/whats-new/dotnet-9/runtime">What’s new in the .NET 9 runtime</a>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73b1cb96c13f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/c-sharp-programming/feature-switches-in-net-9-73b1cb96c13f">Feature Switches in .NET 9</a> was originally published in <a href="https://medium.com/c-sharp-programming">Any Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>