<?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 Tech Beast on Medium]]></title>
        <description><![CDATA[Stories by Tech Beast on Medium]]></description>
        <link>https://medium.com/@raindefiance?source=rss-f5955b00edc6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-k8sZmiTMfman0KB2DHLng.jpeg</url>
            <title>Stories by Tech Beast on Medium</title>
            <link>https://medium.com/@raindefiance?source=rss-f5955b00edc6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 22 May 2026 13:15:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@raindefiance/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[String Enums in C# and TypeScript: Getting the Value Properly]]></title>
            <link>https://medium.com/@raindefiance/string-enums-in-c-and-typescript-getting-the-value-properly-788e244b9bed?source=rss-f5955b00edc6------2</link>
            <guid isPermaLink="false">https://medium.com/p/788e244b9bed</guid>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[enum]]></category>
            <dc:creator><![CDATA[Tech Beast]]></dc:creator>
            <pubDate>Thu, 12 Feb 2026 10:45:20 GMT</pubDate>
            <atom:updated>2026-02-12T10:45:20.834Z</atom:updated>
            <content:encoded><![CDATA[<p>Enums represent a fixed set of values, but when working with APIs, logging, or UI output, you typically need the string value, not the enum itself.</p><p>This article focuses exclusively on:</p><p>✅ String enums (or string-based enum patterns)<br> ✅ How to retrieve their string values<br> ✅ Compile-time vs runtime behavior</p><h3>C# and “String Enums”</h3><p><strong>Important clarification:</strong> C# does not support true string-backed enums. All C# enums are backed by numeric types.</p><p>When we discuss “string enums” in C#, we’re actually referring to:</p><ul><li>Getting the enum name as a string</li><li>Mapping enum values to custom string representations</li></ul><h3>1. Getting the Enum Name as a String</h3><pre>enum Status<br>{<br>    Pending,<br>    Approved,<br>    Rejected<br>}</pre><pre>Status status = Status.Approved;<br>string value = status.ToString();</pre><p><strong>Result:</strong> &quot;Approved&quot;</p><p><strong>What happens:</strong></p><ul><li><strong>Compile time</strong> → Type safety enforced</li><li><strong>Runtime</strong> → String generated from enum metadata</li></ul><p>This is the simplest and most common approach.</p><h3>2. Getting the Name at Compile Time with nameof</h3><p>When referencing a specific member directly:</p><pre>string value = nameof(Status.Approved);</pre><p><strong>Result:</strong> &quot;Approved&quot;</p><p><strong>Why this is powerful:</strong></p><ul><li>Fully resolved at compile time</li><li>Refactor-safe</li><li>Zero runtime cost</li><li>No reflection required</li></ul><p><strong>Important:</strong> nameof only works when referencing a known member—not with variables.</p><h3>3. Custom String Values (Display Pattern)</h3><p>Sometimes your API requires &quot;waiting_for_approval&quot; instead of &quot;Pending&quot;.</p><p><strong>Implementation using attributes:</strong></p><pre>using System.ComponentModel.DataAnnotations;<br><br>enum Status<br>{<br>    [Display(Name = &quot;waiting_for_approval&quot;)]<br>    Pending,<br>    [Display(Name = &quot;approved&quot;)]<br>    Approved<br>}</pre><p><strong>Extension method:</strong></p><pre>using System.Reflection;<br><br>public static class EnumExtensions<br>{<br>    public static string GetDisplayName(this Enum value)<br>    {<br>        var field = value.GetType().GetField(value.ToString());<br>        var attribute = field?.GetCustomAttribute&lt;DisplayAttribute&gt;();<br>        return attribute?.Name ?? value.ToString();<br>    }<br>}</pre><p><strong>Usage:</strong></p><pre>string value = status.GetDisplayName();</pre><p><strong>What happens:</strong></p><ul><li><strong>Compile time</strong> → Attribute defined</li><li><strong>Runtime</strong> → Reflection lookup</li></ul><p><strong>Use this when:</strong></p><ul><li>API responses need controlled string formats</li><li>Localization is required</li><li>Internal naming differs from external representation</li></ul><p><strong>Caution:</strong> Avoid in performance-critical loops due to reflection overhead.</p><h3>TypeScript: Real String Enums</h3><p>Unlike C#, TypeScript supports true string-backed enums.</p><h3>1. String Enum Definition</h3><pre>enum Status {<br>  Pending = &quot;PENDING&quot;,<br>  Approved = &quot;APPROVED&quot;,<br>  Rejected = &quot;REJECTED&quot;<br>}</pre><p>This is a genuine string-backed enum.</p><h3>2. Getting the Value</h3><pre>const status = Status.Approved;<br>console.log(status);</pre><p><strong>Output:</strong> &quot;APPROVED&quot;</p><p>No conversion needed — the value is already a string.</p><h3>What Happens Internally</h3><p>TypeScript compiles this to:</p><pre>var Status;<br>(function (Status) {<br>  Status[&quot;Pending&quot;] = &quot;PENDING&quot;;<br>  Status[&quot;Approved&quot;] = &quot;APPROVED&quot;;<br>  Status[&quot;Rejected&quot;] = &quot;REJECTED&quot;;<br>})(Status || (Status = {}));</pre><p><strong>At runtime:</strong></p><ul><li>Status is a JavaScript object</li><li>Each member is a string property</li><li>Access is simple property lookup</li></ul><h3>Compile Time vs Runtime (TypeScript)</h3><p>Stage What Happens Compile time Type checking Build time Enum emitted as JS object Runtime Property access returns string</p><p><strong>Key point:</strong> There’s no conversion happening. You’re simply retrieving a string property from an object.</p><h3>Modern Alternative in TypeScript</h3><p>Many teams now prefer this pattern:</p><pre>const Status = {<br>  Pending: &quot;PENDING&quot;,<br>  Approved: &quot;APPROVED&quot;,<br>  Rejected: &quot;REJECTED&quot;<br>} as const;<br><br>type Status = typeof Status[keyof typeof Status];</pre><p><strong>Getting the value:</strong></p><pre>const status = Status.Approved;</pre><p><strong>Why this is popular:</strong></p><ul><li>No special enum emission</li><li>Cleaner JavaScript output</li><li>Better tree shaking</li><li>Fully type-safe</li></ul><p>At runtime, this is simply a plain object.</p><h3>C# vs TypeScript: String Behavior Comparison</h3><p>Feature C# TypeScript True string-backed enum ❌ No ✅ Yes .ToString() needed ✅ Yes ❌ No Compile-time constant option nameof Direct member Runtime reflection needed For custom strings No Runtime overhead Minimal Object property lookup</p><h3>Best Practice Summary</h3><h3>In C#</h3><ul><li>Use .ToString() for simple string names</li><li>Use nameof() when referencing known members at compile time</li><li>Use attributes + extension methods for controlled API output</li><li>Remember: C# enums are numeric under the hood</li></ul><h3>In TypeScript</h3><ul><li>Use string enums when modeling domain values</li><li>No conversion required — the value is already a string</li><li>Prefer as const objects in modern frontend projects for better JavaScript output</li></ul><p>Thanks for reading! 👏 If this helped clarify string enums for you, feel free to share it with your team. 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=788e244b9bed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Node.js: Single-Threaded at Heart, Multi-Threaded in Practice]]></title>
            <link>https://medium.com/@raindefiance/node-js-single-threaded-at-heart-multi-threaded-in-practice-7551a7da5cd1?source=rss-f5955b00edc6------2</link>
            <guid isPermaLink="false">https://medium.com/p/7551a7da5cd1</guid>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[libuv]]></category>
            <category><![CDATA[c]]></category>
            <dc:creator><![CDATA[Tech Beast]]></dc:creator>
            <pubDate>Mon, 08 Sep 2025 08:33:54 GMT</pubDate>
            <atom:updated>2025-09-08T08:33:54.333Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*Wf8cMOo4kA88J1AV.png" /></figure><h3>The problem</h3><p>Alright so at this point, I’m sure all of us know that NodeJS is single threaded but yet somehow it manages to handle hundreds of requests without using threads like Java or Python. How does it stay non-blocking while still doing so much in parallel? It’s because of the <strong>event loop</strong>.</p><h3>How nodeJS handles concurrency</h3><p>So normally Java would handle concurrency using <strong>multiple threads </strong>where<strong> </strong>each request might even spin up its own thread. But nodeJS takes a different route. It’s built on <strong>a single-threaded event loop</strong>. And yet, it still manages to handle <strong>I/O-heavy workloads </strong>efficiently. This event loop is the core mechanism that lets Node.js do async stuff in a <strong>synchronous-looking way</strong>. When you run setTimeout() or make a DB call, Node doesn’t wait around. It offloads that task, continues running other code, and comes back to your result <em>later</em>. This is what the normal flow would look like.</p><ul><li>So call stack will execute your code line by line.</li><li>Node APIs like http, setTimeout or even filesystem APIs like reading or writing to a file, all of these are offloaded.</li><li>Now comes the game changer. NodeJS internally uses this library called <strong>libuv, </strong>a C library, that manages a thread pool and handles things like file I/O or TCP. But I just said, NodeJS is single thread. What is this thread pool that libuv manages? I’ll come to that.</li><li>Then there’s the <strong>callback queue</strong>. The async tasks would have a callback that runs after that task is complete. These callbacks are queued inside this callback queue.</li><li><strong>Event Loop</strong> — constantly checks if the stack is empty and pulls the next thing from the queue.</li></ul><h3>libuv</h3><p>Okay let’s get back to libuv now. This library handles the lower-level async operations using a <strong>thread pool </strong>— but abstracted away from you. Think of it as the behind-the-scenes <strong>engine</strong> that powers most of Node.js’s non-blocking behavior. For example, when you do fs.readFile, Node doesn’t directly know how to access the file system asynchronously. Instead, it <strong>delegates</strong> this task to libuv. libuv spins up a thread from its internal pool to do the file reading, and then calls you back when it’s done. If you look at libuv’s github documentation, you’ll see all of these features.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/0*mWM4rwIp7xga5637.png" /></figure><p>It’s all mostly non-blocking async operational features. You’ll also see child processes and thread pool in this list. So you do have options to spawn child processes and a pool of threads with libuv.</p><p>Child processes and threads are different in their own sense and <a href="https://www.youtube.com/playlist?list=PL62km_yqC3ZEV0wKbLbd3CG-2zt3oDkes">I’ve a separate video series covering both. You can check it out.</a> But for now, let’s see the thread action with in an example.</p><p>I have a simple node.js script here.</p><pre>const crypto = require(&#39;crypto&#39;);<br>const start = Date.now();<br>for (let i = 0; i &lt; 6; i++) {<br>  crypto.pbkdf2(&#39;password&#39;, &#39;salt&#39;, 100000, 512, &#39;sha512&#39;, () =&gt; {<br>    console.log(`Done in: ${Date.now() - start}ms`);<br>  });<br>}</pre><ul><li>I’m using the native, crypto module to do some <strong>heavy cryptographic work</strong>, specifically pbkdf2, a password-based key derivation function — it’s CPU-intensive.</li><li>I’m saving the current timestamp which I’ll later subtract to calculate <strong>how long the operation actually took</strong>.</li><li>There’s a for loop that’ll run 6 times. So technically, I’ll be kicking off 6 pbkdf2 operations.</li></ul><p>Now pbkdf2 is asynchronous and just like DNS resolution or file system operations, behind the scenes these encryption operations are also offloaded to a thread pool that’s managed by libuv and not the main thread. When each of these operations finish, the event loop <strong>that’s also part of libuv and not the v8 engine</strong>, moves the callback for these operations to the callstack inside the v8 engine. V8 engine is then responsible to <strong>actually execute the callback function</strong>.</p><p>If you run this, you’ll see 4 of the 6 operations take almost equal time, but the remaining 2 will take way more than that. That’s because by default, <strong>there are 4 threads</strong> in this thread pool. So in our case 6 tasks were launched but only 4 can run in parallel. The remaining 2 had to wait in a queue and that’s why you’ll see <strong>some finish quickly</strong>, and <strong>the rest later</strong>, once a thread becomes available.</p><p>We can also increase the number of threads. So instead of 4, let’s say I want 6. I can use this env variable before running the script.</p><pre>UV_THREADPOOL_SIZE=6 node your-script.js</pre><p>And now, you’ll see all the tasks run in parallel and take more or less the same amount of time. That’s because all 6 tasks have been assigned to individual threads without any wait time. <strong>This does not mean you can just increase the number of threads to solve your scaling problem. Threads do share memory so too many can cause crashes in your application.</strong></p><p>Node.js since v10.5.0 has native support for worker threads where you can control what runs in parallel but they’re <strong>not commonly used</strong> in typical Node.js apps unless you’re doing CPU-intensive work. To understand why though, we need to look at Node’s design philosophy.</p><h3>NodeJS’s design philosphy</h3><p>Node.js was originally built for <strong>handling lots of concurrent I/O</strong> — what I mean by that is:</p><ul><li>Serving HTTP requests</li><li>Reading/writing to disk</li><li>Talking to databases</li><li>Streaming files and so on</li></ul><p>All of these operations are <strong>I/O-bound</strong>, not CPU-bound. That means:</p><ul><li>The bottleneck is <strong>waiting for things</strong>, not <strong>computing things</strong>.</li><li>So, instead of spinning up new threads, Node just says: “I’ll handle something else while I wait.”</li></ul><p>This <strong>event-driven, single-threaded model</strong> is perfect for that.</p><h3>Worker Threads are for CPU-bound Tasks</h3><p>Now, where <strong>worker threads</strong> shine is with <strong>CPU-intensive tasks</strong>, like:</p><ul><li>Image processing</li><li>Compression</li><li>Complex math or algorithms</li><li>Synchronous crypto operations</li></ul><p>These things <strong>block the main thread</strong> and can freeze your app if not handled off the main event loop. In those cases, you can spin up a worker thread like in Java, and do the heavy lifting in parallel. But here’s the thing: Most backend apps written in Node <strong>don’t do this kind of CPU-heavy work</strong>. They delegate it to services, CDNs, databases, etc.</p><p>What I mean by that is let’s say your app gets a request like: “Send me the latest 10 posts from the database.”</p><p>What happens?</p><ol><li><strong>Your server receives the request</strong> (network I/O)</li><li><strong>You query the database</strong> (database I/O)</li><li><strong>You format the result</strong> (small CPU task)</li><li><strong>You send the response</strong> (network I/O)</li></ol><p>See how most of the work is <strong>waiting on I/O</strong>, not doing hard CPU computations? You’re not doing the heavy lifting — you’re <strong>asking other services</strong> to do it, then just handling the data.</p><p>In contrast, CPU-heavy apps would be things like:</p><ul><li>Image filters or compression</li><li>Running an AI model locally</li><li>Converting videos</li><li>Big data analytics</li></ul><p>These aren’t common in your typical web backend — and when they are needed, people usually <strong>offload them</strong> to a service written in a lower-level language or deployed as a background job (e.g., in Python, Rust, Go, etc.).</p><h3>Conclusion</h3><p>So I hope this made sense and I was able to get my point across. You can literally achieve the same kind of multi threading in NodeJS as you see in Java. It’s just that node was built for heavy I/O scenarios since it’s designed around the event loop and Java on the other hand has a lot more native multi threading features baked in because it was built with the intention of handling more CPU intensive work along with basic I/O work. That’s why you’d see CPU intensive operations being delegated from a node service to a Java service or any other language built for that purpose.</p><p>If you have any other doubts or suggestions, do put them in the comments or you can get in touch with me on any one of my socials. Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7551a7da5cd1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Task.WhenAny in .NET]]></title>
            <link>https://medium.com/@raindefiance/task-whenany-in-net-13f69af179ed?source=rss-f5955b00edc6------2</link>
            <guid isPermaLink="false">https://medium.com/p/13f69af179ed</guid>
            <dc:creator><![CDATA[Tech Beast]]></dc:creator>
            <pubDate>Tue, 05 Aug 2025 21:23:03 GMT</pubDate>
            <atom:updated>2025-08-05T21:34:22.462Z</atom:updated>
            <content:encoded><![CDATA[<h3>Task.WhenAny in .NET</h3><h3>How to Use Asynchronous Task Aggregator Task.WhenAny</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*RKqZiLrI-qHjuMWg3J9I4Q.jpeg" /></figure><p>I’m sure you’ve worked with asynchronous code in .NET. The easiest way to organize it is to use keywords async/await and write your code the same way as synchronous code would. But sometimes, you need to run several independent tasks in a row. Is it the best solution to write this code like a synchronous one? Answers to this question and much more you can find in this article.</p><h3>Introduction</h3><p>When you need to launch several independent tasks, all you need to do is to create the first task, do not wait for its completion, launch the second task, and so on. In the end, you can wait for every task result like this:</p><pre>// collect all async tasks in the list<br>List&lt;Task&lt;TResult&gt;&gt; allTasks = new()<br>{<br>    Task1(),<br>    Task2(),<br>    Task3()<br>};<br><br>await allTasks[0];<br>await allTasks[1];<br>await allTasks[2];<br>// ... proceed</pre><p>But is it a good option? What if you need to launch more asynchronous tasks? The more tasks you have — the more <em>await</em> statements you’re going to write. Sometimes this is the only option you have, but that’s not our case.</p><p>There is a task aggregator available in .NET — <strong>Task.WhenAny</strong>. It creates a single task from a bunch of tasks that will complete when <em>any </em>of the supplied tasks have been completed. It can help to handle task results immediately it finished and not even wait for other tasks’ completion.</p><p>So to handle the result of the asynchronous task just as soon as it finished you can write the next code:</p><pre>// collect all async tasks in the list<br>List&lt;Task&lt;TResult&gt;&gt; allTasks = new()<br>{<br>    Task1(),<br>    Task2(),<br>    Task3()<br>};<br><br>while (allTasks.Count &gt; 0)<br>{<br>    // the code below will return Task&lt;Task&lt;TResult&gt;&gt; - task that wraps your completed task<br>    var finished = await Task.WhenAny(allTasks);    <br>    <br>    // to get the result you can do next<br>    var result = await finished;    <br>    <br>    // ... handle result<br>    // and repeat until allTasks has at least single task<br>    allTasks.Remove(finished);<br>}</pre><p>All you need to do is to collect all your tasks to the collection and pass it as an argument to <em>Task.WhenAny</em>, wait until it returns the very first finished task. You can instantly handle the result, remove the completed task from the collection and repeat these steps for other tasks.</p><p><em>Task.WhenAny</em> always returns a wrapper around your asynchronous task. So if you need to receive the result of the asynchronous task, you must await the wrapper.</p><h3>Task cancellation with Task.WhenAny</h3><p>Now let’s see how to use <em>Task.WhenAny </em>in real-world use cases.</p><p>It happens sometimes you need to cancel the execution of asynchronous code. The common practice is to use <a href="https://docs.microsoft.com/dotnet/api/system.threading.cancellationtoken"><strong>CancellationToken</strong></a><strong>. </strong>But not all methods have an overload that accepts it.</p><p>Let’s check the next example:</p><pre>static Task Task1()<br>{<br>    return Task.Delay(2000);<br>}<br><br>try<br>{<br>    Console.WriteLine(&quot;started&quot;);    <br>    <br>    CancellationTokenSource cts = new(500);<br>    CancellationToken token = cts.Token;    <br>    <br>    await Task.Run(Task1, token);<br>    <br>    Console.WriteLine(&quot;finished wo cancellation&quot;);<br>}<br>catch (Exception)<br>{<br>    Console.WriteLine(&quot;finished with cancellation&quot;);<br>}</pre><p>As you can see, <strong>Task1 </strong>does not have an overload that accepts <em>CancellationToken</em>. I’ve tried to use <em>Task.Run</em> that accepts <em>CancellationToken</em>. But execution result was next:</p><pre>started<br>finished wo cancellation</pre><p>As you can understand from the code above — the task was not canceled. Let’s see how <em>Task.WhenAny</em> can help to resolve it:</p><pre>static Task Task1()<br>{<br>    return Task.Delay(2000);<br>}<br><br>static async Task WithCancellation(Task task, TimeSpan delay)<br>{<br>    Task finished = await Task.WhenAny(task, Task.Delay(delay));<br>    if (finished != task)<br>    {<br>        throw new TaskCanceledException();<br>    }<br>    await finished;<br>}<br><br>try<br>{<br>    Console.WriteLine(&quot;started&quot;);<br>    await WithCancellation(Task1(), TimeSpan.FromMilliseconds(500));<br>    Console.WriteLine(&quot;finished wo cancellation&quot;);<br>}<br>catch (Exception)<br>{<br>    Console.WriteLine(&quot;finished with cancellation&quot;);<br>}</pre><p>Method <strong>WithCancellation </strong>accepts asynchronous task and delay before the cancellation. Based on the delay, another asynchronous task<em> Task.Delay</em> created. If the finished task is not an argument task — delay task finished first. It means you need to raise an exception.</p><p>It’s a little tricky solution because your task will continue to execute in the background and consume resources even after you handle exception. But sometimes, switching context on other stuff is a good option.</p><p>If you need to do the same, but based on <em>CancellationToken,</em> you can create the next overload:</p><pre>static async Task WithCancellation(Task task, CancellationToken cancellationToken)<br>{<br>    Task finished = await Task.WhenAny(task, Task.Delay(Timeout.Infinite, cancellationToken));<br>    if (finished != task)<br>    {<br>        throw new TaskCanceledException();<br>    }<br>    <br>    await finished;<br>}</pre><p>The second task passed to <em>Task.WhenAny </em>is an infinite delay, that would be finished only because the token is cancelled. Based on the methods above, you can create overloads for <em>Task&lt;TResult&gt;</em>.</p><h3>Asynchronous enumerable with Task.WhenAny</h3><p>You can move forward and even create an asynchronous iterator that will return tasks immediately they finish:</p><pre>internal class AsyncTaskEnumerable&lt;TResult&gt; : IAsyncEnumerable&lt;TResult&gt;<br>{<br>    private readonly IEnumerable&lt;Task&lt;TResult&gt;&gt; _tasks;<br><br>    public AsyncTaskEnumerable(IEnumerable&lt;Task&lt;TResult&gt;&gt; tasks)<br>    {<br>        _tasks = tasks;<br>    }<br><br>    public IAsyncEnumerator&lt;TResult&gt; GetAsyncEnumerator(CancellationToken cancellationToken = default)<br>    {<br>        return new AsyncTaskEnumerator(_tasks);<br>    }<br><br>    private class AsyncTaskEnumerator : IAsyncEnumerator&lt;TResult&gt;<br>    {<br>        private readonly List&lt;Task&lt;TResult&gt;&gt; _tasks;<br><br>        public AsyncTaskEnumerator(IEnumerable&lt;Task&lt;TResult&gt;&gt; tasks)<br>        {<br>            _tasks = tasks.ToList();<br>        }<br><br>        public TResult Current { get; private set; }<br><br>        public ValueTask DisposeAsync()<br>        {<br>            return new ValueTask();<br>        }<br><br>        public async ValueTask&lt;bool&gt; MoveNextAsync()<br>        {<br>            if (_tasks.Count == 0)<br>            {<br>                return false;<br>            }<br>            Task&lt;TResult&gt; finished = await Task.WhenAny(_tasks);<br>            Current = await finished;<br>            _ = _tasks.Remove(finished);<br>            return true;<br>        }<br>    }<br>}<br><br>public static class AsyncTaskEnumerableExtensions<br>{<br>    public static IAsyncEnumerable&lt;TResult&gt; ToAsyncEnumerable&lt;TResult&gt;(this IEnumerable&lt;Task&lt;TResult&gt;&gt; tasks)<br>    {<br>        return new AsyncTaskEnumerable&lt;TResult&gt;(tasks);<br>    }<br>}</pre><p>The code below declares async enumerable <strong>AsyncTaskEnumerable </strong>that accepts a collection of launched <em>tasks</em>. <em>MoveNextAsync</em> method passes all the tasks to <em>Task.WhenAny</em>, waits for any to finish and returns it as a result. You can iterate through finished tasks like this:</p><pre>static async Task&lt;int&gt; Task1()<br>{<br>    await Task.Delay(2000);<br>    return 1;<br>}<br><br>static async Task&lt;int&gt; Task2()<br>{<br>    await Task.Delay(1000);<br>    return 2;<br>}<br><br>static async Task&lt;int&gt; Task3()<br>{<br>    await Task.Delay(500);<br>    return 3;<br>}<br><br>Task&lt;int&gt;[] tasks = new[] { Task1(), Task2(), Task3() };<br><br>await foreach (int result in tasks.ToAsyncEnumerable())<br>{<br>    Console.WriteLine(result);<br>}</pre><p>All you need to do is create a collection of tasks, convert it to asynchronous enumerable using the <strong>ToAsyncEnumerable </strong>extension method and iterate through it using <em>await foreach</em>. As a <em>result, </em>you will get task results immediately after they finish.</p><p><strong>But be careful!</strong> The bigger number of asynchronous tasks launched — the more resources you need to handle them all. So limit the number of launched tasks to some reasonable number.</p><h3>Conclussion</h3><p><em>Task.WhenAny</em> helps you to launch several tasks at the same time and get a result immediately after any are finished. You can use this method to handle the result as soon as it is ready.</p><p>Thanks for reading. I’d love to get your feedback!</p><p><em>Have you used Task.WhenAny before? What alternatives to Task.WhenAny you use</em>?🤔</p><p>Please share your thoughts. Happy to discuss it with you 😉</p><h3>Resources</h3><p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.whenany?view=net-9.0&amp;source=post_page-----bb15b6d2f85f---------------------------------------">Task.WhenAny Method (System.Threading.Tasks) | Microsoft Learn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13f69af179ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ 20 Essential Lodash Methods Every JavaScript Developer Should Know]]></title>
            <link>https://medium.com/@raindefiance/20-essential-lodash-methods-every-javascript-developer-should-know-a9b14b6b8101?source=rss-f5955b00edc6------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9b14b6b8101</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[lodash]]></category>
            <dc:creator><![CDATA[Tech Beast]]></dc:creator>
            <pubDate>Sun, 18 May 2025 15:07:56 GMT</pubDate>
            <atom:updated>2025-05-18T15:11:23.674Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*tsaYl2tF7bQBfl9Wz813xA.png" /></figure><p><a href="https://lodash.com/"><strong>Lodash </strong></a>is a popular <strong>JavaScript </strong>library that provides utility functions for simplifying and streamlining common programming tasks. It offers a wide range of methods to manipulate and work with arrays, objects, functions, and more. In this article, we will explore 20 useful Lodash methods that can enhance your everyday coding experience and improve code efficiency.</p><h3>1. _.get()</h3><p>The _.get() method retrieves the value of a nested property in an object.</p><pre>const user = { name: { first: &#39;John&#39;, last: &#39;Doe&#39; } };<br>const firstName = _.get(user, &#39;name.first&#39;);<br>// firstName: &#39;John&#39;</pre><h3>2. _.isEmpty()</h3><p>_.isEmpty() checks if a value is an empty object, array, map, or set.</p><pre>const emptyArray = [];<br>const isEmpty = _.isEmpty(emptyArray);<br>// isEmpty: true</pre><h3>3. _.map()</h3><p>The _.map() method allows you to iterate over each element in an array or object and apply a function to transform the elements based on the given criteria.</p><pre>const doubledNumbers = _.map([1, 2, 3], num =&gt; num * 2);<br>// doubledNumbers: [2, 4, 6]</pre><h3>4. _.filter()</h3><p>The _.filter() method lets you create a new array with elements that pass a certain condition or criteria.</p><pre>const evenNumbers = _.filter([1, 2, 3, 4], num =&gt; num % 2 === 0);<br>// evenNumbers: [2, 4]</pre><h3>5. _.reduce()</h3><p>_.reduce() allows you to reduce an array or object to a single value by applying an accumulating function.</p><pre>const sum = _.reduce([1, 2, 3], (acc, num) =&gt; acc + num, 0);<br>// sum: 6</pre><h3>6. _.merge()</h3><p>The _.merge() method merges two or more objects by deeply combining their properties.</p><pre>const obj1 = { a: 1 };<br>const obj2 = { b: 2 };<br>const mergedObj = _.merge(obj1, obj2);<br>// mergedObj: { a: 1, b: 2 }</pre><h3>7. _.debounce()</h3><p>_.debounce() is useful for delaying a function’s execution until after a specified amount of time has passed since the last invocation. This is particularly helpful for handling events like resizing or scrolling.</p><pre>const debouncedFunction = _.debounce(() =&gt; console.log(&#39;Function debounced&#39;), 300);</pre><h3>8. _.throttle()</h3><p>Similar to _.debounce(), _.throttle() limits the number of times a function can be called over a specified time interval.</p><pre>const throttledFunction = _.throttle(() =&gt; console.log(&#39;Function throttled&#39;), 300);</pre><h3>9. _.flatten()</h3><p>The _.flatten() method flattens a nested array into a single array.</p><pre>const nestedArray = [1, [2, [3, [4]], 5]];<br>const flattenedArray = _.flatten(nestedArray);<br>// flattenedArray: [1, 2, 3, 4, 5]</pre><h3>10. _.orderBy()</h3><p>_.orderBy() allows you to sort an array of objects based on specified properties and order.</p><pre>const users = [<br>  { name: &#39;John&#39;, age: 30 },<br>  { name: &#39;Alice&#39;, age: 25 },<br>];<br>const sortedUsers = _.orderBy(users, [&#39;age&#39;], [&#39;desc&#39;]);<br>// sortedUsers: [{ name: &#39;John&#39;, age: 30 }, { name: &#39;Alice&#39;, age: 25 }]</pre><h3>11. _.uniq()</h3><p>The _.uniq() method creates a new array with unique elements.</p><pre>const arrayWithDuplicates = [1, 2, 2, 3, 4, 4, 5];<br>const uniqueArray = _.uniq(arrayWithDuplicates);<br>// uniqueArray: [1, 2, 3, 4, 5]</pre><h3>12. _.isEqual()</h3><p>_.isEqual() compares two values to determine if they are equivalent.</p><pre>const obj1 = { a: 1, b: { c: 2 } };<br>const obj2 = { a: 1, b: { c: 2 } };<br>const isEqual = _.isEqual(obj1, obj2);<br>// isEqual: true</pre><h3>13. _.startsWith()</h3><p>The _.startsWith() method checks if a string starts with a specified prefix.</p><pre>const str = &#39;Hello, world!&#39;;<br>const startsWithHello = _.startsWith(str, &#39;Hello&#39;);<br>// startsWithHello: true</pre><h3>14. _.endsWith()</h3><p>Similar to _.startsWith(), _.endsWith() checks if a string ends with a specified suffix.</p><pre>const str = &#39;Hello, world!&#39;;<br>const endsWithWorld = _.endsWith(str, &#39;world!&#39;);<br>// endsWithWorld: true</pre><h3>15. _.groupBy()</h3><p>The _.groupBy() method groups elements of an array based on a given criterion.</p><pre>const numbers = [6.1, 4.2, 6.3];<br>const groupedByFloor = _.groupBy(numbers, Math.floor);<br>// groupedByFloor: { &#39;4&#39;: [4.2], &#39;6&#39;: [6.1, 6.3] }</pre><h3>16. _.pick()</h3><p>_.pick() allows you to create a new object by picking specific properties from an existing object.</p><pre>const user = { name: &#39;Alice&#39;, age: 30, email: &#39;alice@example.com&#39; };<br>const selectedProperties = _.pick(user, [&#39;name&#39;, &#39;age&#39;]);<br>// selectedProperties: { name: &#39;Alice&#39;, age: 30 }</pre><h3>17. _.omit()</h3><p>The _.omit() method creates a new object with properties omitted from an existing object.</p><pre>const user = { name: &#39;Alice&#39;, age: 30, email: &#39;alice@example.com&#39; };<br>const omittedProperties = _.omit(user, [&#39;email&#39;]);<br>// omittedProperties: { name: &#39;Alice&#39;, age: 30 }</pre><h3>18. _.isEqual()</h3><p>_.isEqual() compares two values to determine if they are equivalent.</p><pre>const obj1 = { a: 1, b: { c: 2 } };<br>const obj2 = { a: 1, b: { c: 2 } };<br>const isEqual = _.isEqual(obj1, obj2);<br>// isEqual: true</pre><h3>19. _.sample()</h3><p>The _.sample() method returns a random element from an array.</p><pre>const numbers = [1, 2, 3, 4, 5];<br>const randomElement = _.sample(numbers);<br>// randomElement: e.g., 3</pre><h3>20. _.zip()</h3><p>_.zip() groups the elements of several arrays into a single array of tuples.</p><pre>const names = [&#39;Alice&#39;, &#39;Bob&#39;, &#39;Charlie&#39;];<br>const ages = [30, 35, 25];<br>const zipped = _.zip(names, ages);<br>// zipped: [[&#39;Alice&#39;, 30], [&#39;Bob</pre><pre>&#39;, 35], [&#39;Charlie&#39;, 25]]</pre><p>In conclusion, <a href="https://lodash.com/"><strong>Lodash </strong></a>provides a wide array of utility functions that can greatly simplify and enhance everyday coding in JavaScript. By leveraging these methods, developers can write cleaner, more efficient, and maintainable code. Understanding and utilizing these Lodash methods can significantly improve your programming workflow and productivity. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9b14b6b8101" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Barrier() and ReadWriteLockSlim() in C# Multithreading]]></title>
            <link>https://medium.com/@raindefiance/understanding-barrier-and-readwritelockslim-in-c-multithreading-e864d5bf0dc6?source=rss-f5955b00edc6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e864d5bf0dc6</guid>
            <category><![CDATA[readerwriterlockslim]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[barriers]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[multithreading]]></category>
            <dc:creator><![CDATA[Tech Beast]]></dc:creator>
            <pubDate>Sun, 23 Mar 2025 16:54:22 GMT</pubDate>
            <atom:updated>2025-03-23T16:55:30.482Z</atom:updated>
            <content:encoded><![CDATA[<h3>“Barrier”: <strong>Stagewise synchronizing Multiple Threads</strong></h3><p>Thread.Barrier is a synchronization primitive that enables multiple threads to synchronize their actions. It allows a set of threads to wait for each other to reach a certain point of execution before any of them proceeds.</p><p>Here’s an example demonstrating Thread.Barrier:</p><pre>using System;<br>using System.Threading;<br>using System.Threading.Tasks;<br><br>public class Program<br>{<br>    private static Barrier _barrier = new Barrier(3); // 3 participants<br><br>    public static void Main()<br>    {<br>        Console.WriteLine(&quot;Starting Barrier Demonstration&quot;);<br><br>        Task task1 = Task.Run(() =&gt; DoWork(&quot;Task 1&quot;));<br>        Task task2 = Task.Run(() =&gt; DoWork(&quot;Task 2&quot;));<br>        Task task3 = Task.Run(() =&gt; DoWork(&quot;Task 3&quot;));<br><br>        Task.WaitAll(task1, task2, task3);<br><br>        Console.WriteLine(&quot;Barrier Demonstration Completed&quot;);<br>    }<br><br>    public static void DoWork(string taskName)<br>    {<br>        Console.WriteLine($&quot;{taskName} started&quot;);<br>        Thread.Sleep(new Random().Next(1000, 3000)); // Simulate work<br>        Console.WriteLine($&quot;{taskName} waiting at barrier&quot;);<br>        <br>        _barrier.SignalAndWait(); // Wait for other threads<br><br>        Console.WriteLine($&quot;{taskName} passed barrier&quot;);<br>        Thread.Sleep(new Random().Next(1000, 3000)); // More work<br>        Console.WriteLine($&quot;{taskName} completed&quot;);<br>    }<br>}</pre><p><strong>Output:</strong></p><pre>Starting Barrier Demonstration<br>Task 1 started<br>Task 2 started<br>Task 3 started<br>Task 2 waiting at barrier<br>Task 1 waiting at barrier<br>Task 3 waiting at barrier<br>Task 2 passed barrier<br>Task 1 passed barrier<br>Task 3 passed barrier<br>Task 1 completed<br>Task 3 completed<br>Task 2 completed<br>Barrier Demonstration Completed</pre><p>In this example:</p><ol><li>We create a Barrier with 3 participants, corresponding to our three tasks.</li><li>Each task performs some initial work (simulated by a random sleep).</li><li>All tasks then call _barrier.SignalAndWait(). This method does two things:</li></ol><ul><li>It signals that the task has reached the barrier.</li><li>It makes the task wait until all other participants have also reached the barrier.</li></ul><p>4. Once all three tasks have reached the barrier, they are all released simultaneously.</p><p>5. The tasks then perform some final work before completing.</p><p>The key point here is that <strong>Thread.Barrier</strong> ensures that all participating threads reach a certain point in their execution before any of them are allowed to proceed further. This is useful in scenarios where you need to synchronize multiple threads at specific points in their execution.</p><h3>“ReadWriteLockSlim”: Concurrent reads, exclusive writes synchronization.</h3><p>ReadWriteLockSlim is a lightweight synchronization primitive that’s particularly useful when you have a resource that’s frequently read but infrequently written. It allows for concurrent read operations while ensuring exclusive access for write operations. This makes it particularly useful for implementing thread-safe classes with multiple methods that need to access shared data.</p><p>Key features of ReadWriteLockSlim for multi-method thread safety:</p><ol><li>Granular locking: You can apply different lock modes (read, upgradeable read, or write) to different methods based on their access patterns.</li><li>Performance optimization: It allows multiple threads to read simultaneously, improving performance in read-heavy scenarios.</li><li>Upgrade capability: You can upgrade from a read lock to a write lock, which is useful for methods that may need to write based on certain conditions.</li><li>Reentrance: Supports recursive locking, allowing a thread to enter the same lock multiple times.</li><li>Timeout options: Provides methods to attempt acquiring locks with timeouts, preventing deadlocks.</li></ol><p>When implementing a thread-safe class with multiple methods:</p><ul><li>Use EnterReadLock() for methods that only read shared data.</li><li>Use EnterWriteLock() for methods that modify shared data.</li><li>Use EnterUpgradeableReadLock() for methods that mostly read but may need to write.</li></ul><p>By consistently applying these locks across all methods that access shared data, you can ensure thread safety for the entire class, preventing race conditions and data corruption in multi-threaded environments.</p><h3>Example: Using ReadWriteLockSlim</h3><p>Let’s create an example that demonstrates the use of ReadWriteLockSlim in a scenario where we will showcase multiple concurrent reads while ensuring exclusive access for writes, making it efficient for scenarios with frequent reads and occasional writes.</p><pre>using System;<br>using System.Threading;<br>using System.Threading.Tasks;<br><br>class Program<br>{<br>    static ReaderWriterLockSlim rwLock = new ReaderWriterLockSlim();<br>    static int sharedResource = 0;<br><br>    static void Main()<br>    {<br>        Task[] tasks = new Task[5];<br>        for (int i = 0; i &lt; 5; i++)<br>        {<br>            tasks[i] = i % 2 == 0 ? Task.Run(ReadResource) : Task.Run(WriteResource);<br>        }<br><br>        Task.WaitAll(tasks);<br>    }<br><br>    static void ReadResource()<br>    {<br>        rwLock.EnterReadLock();<br>        try<br>        {<br>            Console.WriteLine($&quot;Thread {Thread.CurrentThread.ManagedThreadId} reading: {sharedResource}&quot;);<br>            Thread.Sleep(100); // Simulate some work<br>        }<br>        finally<br>        {<br>            rwLock.ExitReadLock();<br>        }<br>    }<br><br>    static void WriteResource()<br>    {<br>        rwLock.EnterWriteLock();<br>        try<br>        {<br>            sharedResource++;<br>            Console.WriteLine($&quot;Thread {Thread.CurrentThread.ManagedThreadId} writing: {sharedResource}&quot;);<br>            Thread.Sleep(100); // Simulate some work<br>        }<br>        finally<br>        {<br>            rwLock.ExitWriteLock();<br>        }<br>    }<br>}</pre><p>Output:</p><pre>Thread 4 reading: 0<br>Thread 5 reading: 0<br>Thread 6 writing: 1<br>Thread 7 reading: 1<br>Thread 8 writing: 2</pre><p><strong>Explanation of the output:</strong></p><ul><li>The output may vary due to the nature of concurrent execution, but it demonstrates key behaviors of ReadWriteLockSlim.</li><li>Multiple threads can read simultaneously (threads 4 and 5 both read 0).</li><li>Write operations are exclusive (threads 6 and 8 write sequentially).</li><li>Read operations see the updated value after a write (thread 7 reads 1 after it was incremented).</li></ul><p>This example showcases how ReadWriteLockSlim allows multiple concurrent reads while ensuring exclusive access for writes, making it efficient for scenarios with frequent reads and occasional writes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e864d5bf0dc6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[StackFrame vs StackTrace in C#]]></title>
            <link>https://medium.com/@raindefiance/stackframe-vs-stacktrace-in-c-c9ff4915fc4b?source=rss-f5955b00edc6------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9ff4915fc4b</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Tech Beast]]></dc:creator>
            <pubDate>Thu, 05 Dec 2024 10:10:24 GMT</pubDate>
            <atom:updated>2024-12-05T14:28:05.859Z</atom:updated>
            <content:encoded><![CDATA[<p>In C#, <strong>StackFrame</strong> and <strong>StackTrace</strong> are classes in the System.Diagnostics namespace used for analyzing the call stack of a program. They have different purposes and functionalities:</p><h3>1. StackFrame</h3><ul><li>Represents a single frame in the call stack.</li><li>Contains information about a method invocation, including the method name, file name, line number, and column number (if debugging symbols are available).</li><li>Can be used to inspect specific details about a method at a particular level of the call stack.</li></ul><h4>Key Properties and Methods</h4><ul><li><strong>GetMethod()</strong>: Gets the method associated with the stack frame.</li><li><strong>GetFileName()</strong>: Gets the file name containing the method (if debugging symbols are available).</li><li><strong>GetFileLineNumber()</strong>: Gets the line number in the source file where the method is defined.</li><li><strong>GetFileColumnNumber()</strong>: Gets the column number in the source file.</li></ul><h4>Usage Example</h4><pre>using System.Diagnostics;<br><br>class Program<br>{<br>    static void Main()<br>    {<br>        TestMethod();<br>    }    <br>    <br>    static void TestMethod()<br>    {<br>        StackFrame frame = new StackFrame(1, true); // Get the previous frame (1 level up) with file and line info<br>        var method = frame.GetMethod();<br>        Console.WriteLine($&quot;Method: {method.Name}&quot;);<br>        Console.WriteLine($&quot;File: {frame.GetFileName()}&quot;);<br>        Console.WriteLine($&quot;Line: {frame.GetFileLineNumber()}&quot;);<br>    }<br>}</pre><h3>2. StackTrace</h3><ul><li>Represents the entire stack trace of the program at a particular point in time.</li><li>A stack trace is a collection of StackFrame objects, one for each method call in the call stack.</li><li>Typically used to analyze the complete path leading to an exception or to debug the flow of method calls.</li></ul><h4>Key Properties and Methods</h4><ul><li><strong>FrameCount</strong>: Gets the number of frames in the stack trace.</li><li><strong>GetFrame(int index)</strong>: Gets a specific frame from the stack trace.</li><li><strong>ToString()</strong>: Provides a string representation of the entire stack trace.</li></ul><h4>Usage Example</h4><pre>using System.Diagnostics;<br><br>class Program<br>{<br>    static void Main()<br>    {<br>        TestMethod();<br>    }    <br>    <br>    static void TestMethod()<br>    {<br>        StackTrace trace = new StackTrace(true); // Capture stack trace with file and line info<br>        foreach (StackFrame frame in trace.GetFrames())<br>        {<br>            Console.WriteLine($&quot;Method: {frame.GetMethod().Name}, File: {frame.GetFileName()}, Line: {frame.GetFileLineNumber()}&quot;);<br>        }<br>    }<br>}</pre><h3>Key Differences</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*_29ttXhLuVOQIEY129iMqA.jpeg" /></figure><h3>When to Use</h3><ul><li>Use <strong>StackFrame</strong> when you need details about a specific method in the stack.</li><li>Use <strong>StackTrace</strong> when you need an overview of the entire call stack or want to analyze the execution flow.</li></ul><p><strong>Happy Coding </strong><em>🎉🎉 .</em></p><p><strong>Tap the </strong>👏 <strong>button if you found this article useful!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9ff4915fc4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C# 13 New Features Explained]]></title>
            <link>https://medium.com/@raindefiance/c-13-new-features-explained-76bb6c4e59bf?source=rss-f5955b00edc6------2</link>
            <guid isPermaLink="false">https://medium.com/p/76bb6c4e59bf</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[techupdates]]></category>
            <category><![CDATA[csharp-13]]></category>
            <dc:creator><![CDATA[Tech Beast]]></dc:creator>
            <pubDate>Mon, 14 Oct 2024 01:08:52 GMT</pubDate>
            <atom:updated>2024-10-14T01:10:31.364Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*15Uj0hn9CTzoWBOH" /></figure><p>Welcome to my blog! Today, we’re diving into the exciting new features of C# 13. With the release of Visual Studio 2022 and its various previews, C# 13 has introduced several enhancements that improve functionality and developer experience. Let’s explore these features in detail.</p><h4>Enhanced Params Collections</h4><p>The first major feature in C# 13 is the enhanced params collections. This allows you to pass a variety of collection types — beyond just arrays — using the params keyword. You can now use lists, spans, and enumerables seamlessly.</p><p><strong><em>What Are Param Collections?</em></strong></p><p>The params keyword in C# allows a method to accept a variable number of arguments, which must be a single-dimensional array. This parameter must be the last in the method signature, and only one params parameter is allowed per method.</p><p><strong><em>How Is It Used?</em></strong></p><p>Example of a method to calculate the sum of integers:</p><pre>List&lt;int&gt; numbers = new List&lt;int&gt; { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };<br>int results = CalculateSum(numbers.ToArray());</pre><pre>Console.WriteLine(results);</pre><pre>int CalculateSum(params int[] numbers)<br>{<br>    return numbers.Sum();</pre><pre>}</pre><p><strong><em>Limitations and Performance Considerations</em></strong></p><p>Using params involves creating an array, which can affect performance, especially in loops or performance-critical code. Additionally, only one params parameter is allowed per method, and it must be the last parameter.</p><p><strong><em>Changes in C# 13</em></strong></p><p>C# 13 enhances the params keyword with:</p><ul><li><strong>Support for Multi-Dimensional Arrays:</strong> Simplifies method calls and improves readability.</li><li><strong>Improved Type Inference:</strong> Better integration with generic methods and complex types.</li><li><strong>Performance Optimizations:</strong> Reduced overhead and improved performance for high-frequency method calls.</li></ul><p><strong>Examples</strong></p><p>Enhanced CalculateSum method in C# 13:</p><pre>List&lt;int&gt; numbers = new List&lt;int&gt; { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };<br>int results = CalculateSum(numbers);</pre><pre>Console.WriteLine(results);</pre><pre>int CalculateSum(params List&lt;int&gt; numbers)<br>{<br>    return numbers.Sum();</pre><pre>}</pre><p><strong>Benchmarking the Performance</strong></p><p>To evaluate the performance enhancements, we can set up a benchmark using BenchmarkDotNet:</p><pre>using BenchmarkDotNet.Attributes;<br>using System;<br>using System.Collections.Generic;<br>using System.Linq;[MemoryDiagnoser]<br>public class ParamsBenchmark<br>{<br>    private List&lt;int&gt; numbers;    [GlobalSetup]<br>    public void Setup()<br>    {<br>        numbers = new List&lt;int&gt; { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };<br>    }    <br>    [Benchmark]<br>    public int CalculateSumWithList()<br>    {<br>        return CalculateSum(numbers);<br>    }    <br>    [Benchmark]<br>    public int CalculateSumWithArray()<br>    {<br>        return CalculateSum(numbers.ToArray());<br>    }    <br>    public int CalculateSum(params List&lt;int&gt; numbers)<br>    {<br>        return numbers.Sum();<br>    }    <br>    public int CalculateSum(params int[] numbers)<br>    {<br>        return numbers.Sum();<br>    }<br>}</pre><p><strong>Output</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*ZkiFRRb5TeNNNtib.png" /></figure><p>The benchmark results indicate that the new enhanced params implementation in C# 13 offers better performance with no additional memory overhead. The enhancements in C# 13 make params collections more powerful and efficient, catering to more complex use cases and improving overall performance.</p><h4>New Lock Object</h4><p>Next up is the new lock object, introduced in C# 13 with .NET 9. This feature offers a more efficient mechanism for thread synchronization, improving performance compared to traditional locks.</p><figure><img alt="New lock object example" src="https://cdn-images-1.medium.com/proxy/0*a3KPFsosHxLFzJpH" /></figure><p>Using the new lock object, you can ensure that locks are properly released even if exceptions occur, thanks to the implementation of the dispose pattern. This makes your code safer and more efficient.</p><h4>New Escape Sequence</h4><p>C# 13 also introduces a new escape sequence character, simplifying the process of including escape characters in strings. This new character allows developers to represent escape sequences more intuitively.</p><figure><img alt="New escape sequence example" src="https://cdn-images-1.medium.com/proxy/0*VUFyq14CANDY0Wn5" /></figure><p>This feature is particularly useful when sending control sequences to terminals or devices that interpret escape sequences, enabling more colorful outputs in your applications.</p><h4>Implicit Index Access</h4><p>Another exciting feature is implicit index access. This allows you to use the XOR operator for indexing directly in object initializers, making your code more readable and easier to maintain.</p><figure><img alt="Implicit index access example" src="https://cdn-images-1.medium.com/proxy/0*ZQzik6mwGfRFq742" /></figure><p>With this feature, you can initialize arrays in a more expressive manner, enhancing the clarity of your code when dealing with reverse indexing.</p><h4>Method Group Natural Type</h4><p>The method group natural type feature is designed to improve overload resolution. It helps the compiler better infer the appropriate method to invoke based on the context of the method group.</p><figure><img alt="Method group natural type example" src="https://cdn-images-1.medium.com/proxy/0*dOvcf0qUIz_3JN8o" /></figure><p>This makes it easier to work with method groups, especially when assigning them to delegates or variables, streamlining your coding process.</p><h4>Ref and Unsafe in Async Methods</h4><p>C# 13 enhances the flexibility and performance of async methods and iterators with the introduction of ref and unsafe context. This allows for more efficient memory management and processing within asynchronous operations.</p><figure><img alt="Ref and unsafe in async methods example" src="https://cdn-images-1.medium.com/proxy/0*Qbkm-r2VeW9t0ehw" /></figure><p>With this new feature, you can declare reference local variables that retain their references across async boundaries, improving the performance of your applications.</p><h4>Extension Types</h4><p>Last but not least, C# 13 introduces extension types, which allow you to add new methods, properties, and even indexes to existing types without modifying the original class.</p><figure><img alt="Extension types example" src="https://cdn-images-1.medium.com/proxy/0*GsMAexrtcrLuFuR8" /></figure><p>This feature simplifies the way you extend functionality, making it easier to enhance existing types while maintaining clean and manageable code.</p><h4>Conclusion</h4><p>In conclusion, C# 13 brings a host of new features that enhance the language’s functionality and improve the developer experience. From enhanced params collections to extension types, these updates are designed to make coding more intuitive and efficient.</p><p>Thank you for joining me on this exploration of C# 13 features. If you’re interested in more tutorials and in-depth explanations, please let me know in comments!</p><p>Stay tuned for more updates and happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76bb6c4e59bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C# : String Literals]]></title>
            <link>https://medium.com/@raindefiance/c-string-literals-b2acaa250934?source=rss-f5955b00edc6------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2acaa250934</guid>
            <category><![CDATA[string-manipulation]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <dc:creator><![CDATA[Tech Beast]]></dc:creator>
            <pubDate>Mon, 14 Oct 2024 00:42:32 GMT</pubDate>
            <atom:updated>2024-10-14T00:44:27.389Z</atom:updated>
            <content:encoded><![CDATA[<h3>C# : String Literals Manipulation</h3><h3>Simple Strings</h3><p>Every language needs a type for storing text, that’s the String class/string keyword. It’s what is used mainly in C# and has been there since day 1:</p><pre>var text = &quot;I thought we had literal strings&quot;;<br>WriteLine(text);</pre><p>We could use embedded quotes, but we needed to escape them (or other things like tabs, line breaks):</p><pre>text = &quot;John \&quot;Quincy\&quot; Adams&quot;;</pre><p>We didn’t have a good solution for multi-line, so we ended up with monstrosities (or using a StringBuilder):</p><pre>text = &quot;First Line\n&quot;;<br>text += &quot;Second Line\n&quot;;<br>text += &quot;Third Line&quot;;</pre><h3>String Interpolation</h3><p>Some time, later C# introduced a way to have strings just use interpolation (instead of the dreaded string.Format(…)):</p><pre>text = $&quot;This is an interpolated string: {someName} - {someName.Length}&quot;;</pre><p>The dollar sign said that it should expect C# code inside brackets.</p><p>But this introduced a need to double bracket if you needed a bracket in string:</p><pre>text = $&quot;This is an interpolated string: {{ {someName} }}&quot;;</pre><p>A compromise to support this better way of building strings. Of course, that made JSON in strings pretty ugly:</p><pre>text = $&quot;{{ \&quot;name\&quot;: \&quot;Shawn\&quot; }}&quot;;</pre><p>Interpolated strings support all the capabilities of the <a href="https://learn.microsoft.com/en-us/dotnet/standard/base-types/composite-formatting">string composite formatting</a> feature. That makes them a more <strong>readable alternative </strong>to the use of the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.string.format"><strong>String.Format</strong></a> method.</p><h3>How to specify a format string for an interpolation expression</h3><p>To specify a format string that is supported by the type of the expression result, follow the interpolation expression with a colon (“:”) and the format string:</p><pre>{&lt;interpolationExpression&gt;:&lt;formatString&gt;}</pre><p>The following example shows how to specify standard and custom format strings for expressions that produce date and time or numeric results:</p><pre>var date = new DateTime(1731, 11, 25);<br>Console.WriteLine($&quot;On {date:dddd, MMMM dd, yyyy} L. Euler introduced the letter e to denote {Math.E:F5}.&quot;);<br>// Output:<br>// On Sunday, November 25, 1731 L. Euler introduced the letter e to denote 2.71828.</pre><p>For more information, see the <a href="https://learn.microsoft.com/en-us/dotnet/standard/base-types/composite-formatting#format-string-component">Format string component</a> section of the <a href="https://learn.microsoft.com/en-us/dotnet/standard/base-types/composite-formatting">Composite formatting</a> article.</p><h3>How to control the field width and alignment of the formatted interpolation expression</h3><p>To specify the minimum field width and the alignment of the formatted expression result, follow the interpolation expression with a comma (“,”) and the constant expression:</p><pre>{&lt;interpolationExpression&gt;,&lt;alignment&gt;}</pre><p>If the <em>alignment</em> value is positive, the formatted expression result is right-aligned; if negative, it’s left-aligned.</p><p>If you need to specify both alignment and a format string, start with the alignment component:</p><pre>{&lt;interpolationExpression&gt;,&lt;alignment&gt;:&lt;formatString&gt;}</pre><p>The following example shows how to specify alignment and uses pipe characters (“|”) to delimit text fields:</p><pre>const int NameAlignment = -9;<br>const int ValueAlignment = 7;<br>double a = 3;<br>double b = 4;<br>Console.WriteLine($&quot;Three classical Pythagorean means of {a} and {b}:&quot;);<br>Console.WriteLine($&quot;|{&quot;Arithmetic&quot;,NameAlignment}|{0.5 * (a + b),ValueAlignment:F3}|&quot;);<br>Console.WriteLine($&quot;|{&quot;Geometric&quot;,NameAlignment}|{Math.Sqrt(a * b),ValueAlignment:F3}|&quot;);<br>Console.WriteLine($&quot;|{&quot;Harmonic&quot;,NameAlignment}|{2 / (1 / a + 1 / b),ValueAlignment:F3}|&quot;);<br>// Output:<br>// Three classical Pythagorean means of 3 and 4:<br>// |Arithmetic|  3.500|<br>// |Geometric|  3.464|<br>// |Harmonic |  3.429|</pre><p>As the example output shows, if the length of the formatted expression result exceeds specified field width, the <em>alignment</em> value is ignored.</p><p>For more information, see the <a href="https://learn.microsoft.com/en-us/dotnet/standard/base-types/composite-formatting#alignment-component">Alignment component</a> section of the <a href="https://learn.microsoft.com/en-us/dotnet/standard/base-types/composite-formatting">Composite formatting</a> article.</p><h3>How to use escape sequences in an interpolated string</h3><p>Interpolated strings support all escape sequences that can be used in ordinary string literals. For more information, see <a href="https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/#string-escape-sequences">String escape sequences</a>.</p><p>To interpret escape sequences literally, use a <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/verbatim">verbatim</a> string literal. An interpolated verbatim string starts with the both $ and @ characters. You can use $ and @ in any order: both $@&quot;...&quot; and @$&quot;...&quot; are valid interpolated verbatim strings.</p><p>To include a brace, “{“ or “}”, in a result string, use two braces, “{{“ or “}}”. For more information, see the <a href="https://learn.microsoft.com/en-us/dotnet/standard/base-types/composite-formatting#escaping-braces">Escaping braces</a> section of the <a href="https://learn.microsoft.com/en-us/dotnet/standard/base-types/composite-formatting">Composite formatting</a> article.</p><p>The following example shows how to include braces in a result string and construct a verbatim interpolated string:</p><pre>var xs = new int[] { 1, 2, 7, 9 };<br>var ys = new int[] { 7, 9, 12 };<br>Console.WriteLine($&quot;Find the intersection of the {{{string.Join(&quot;, &quot;,xs)}}} and {{{string.Join(&quot;, &quot;,ys)}}} sets.&quot;);<br>// Output:<br>// Find the intersection of the {1, 2, 7, 9} and {7, 9, 12} sets.<br>var userName = &quot;Jane&quot;;<br>var stringWithEscapes = $&quot;C:\\Users\\{userName}\\Documents&quot;;<br>var verbatimInterpolated = $@&quot;C:\Users\{userName}\Documents&quot;;<br>Console.WriteLine(stringWithEscapes);<br>Console.WriteLine(verbatimInterpolated);<br>// Output:<br>// C:\Users\Jane\Documents<br>// C:\Users\Jane\Documents</pre><p>Interpolated string also allow you to include special characters inside it. They are indicated by a backslash followed by a character. Some of the most common escape sequences are “\n” for a new line, “\t” for a tab, and “\” for a literal backslash.</p><p>For example:</p><pre>string message = $&quot;This is a message with a\nnew line and a\ttab.&quot;;<br>Console.WriteLine(message);</pre><p>The output of this code will be:</p><pre>This is a message with a<br>new line and a    tab.</pre><h3>How to use a ternary conditional operator ?: in an interpolation expression</h3><p>As the colon (“:”) has special meaning in an item with an interpolation expression, in order to use a <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/conditional-operator">conditional operator</a> in an expression, enclose it in parentheses, as the following example shows:</p><pre>var rand = new Random();<br>for (int i = 0; i &lt; 7; i++)<br>{<br>    Console.WriteLine($&quot;Coin flip: {(rand.NextDouble() &lt; 0.5 ? &quot;heads&quot; : &quot;tails&quot;)}&quot;);<br>}</pre><h3>How to create a culture-specific result string with string interpolation</h3><p>By default, an interpolated string uses the current culture defined by the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.globalization.cultureinfo.currentculture#system-globalization-cultureinfo-currentculture">CultureInfo.CurrentCulture</a> property for all formatting operations.</p><p>Beginning with .NET 6, you can use the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.string.create#system-string-create(system-iformatprovider-system-runtime-compilerservices-defaultinterpolatedstringhandler@)">String.Create(IFormatProvider, DefaultInterpolatedStringHandler)</a> method to resolve an interpolated string to a culture-specific result string, as the following example shows:</p><pre>var cultures = new System.Globalization.CultureInfo[]<br>{<br>    System.Globalization.CultureInfo.GetCultureInfo(&quot;en-US&quot;),<br>    System.Globalization.CultureInfo.GetCultureInfo(&quot;en-GB&quot;),<br>    System.Globalization.CultureInfo.GetCultureInfo(&quot;nl-NL&quot;),<br>    System.Globalization.CultureInfo.InvariantCulture<br>};<br>var date = DateTime.Now;<br>var number = 31_415_926.536;<br>foreach (var culture in cultures)<br>{<br>    var cultureSpecificMessage = string.Create(culture, $&quot;{date,23}{number,20:N3}&quot;);<br>    Console.WriteLine($&quot;{culture.Name,-10}{cultureSpecificMessage}&quot;);<br>}<br>// Output is similar to:<br>// en-US       8/27/2023 12:35:31 PM      31,415,926.536<br>// en-GB         27/08/2023 12:35:31      31,415,926.536<br>// nl-NL         27-08-2023 12:35:31      31.415.926,536<br>//               08/27/2023 12:35:31      31,415,926.536</pre><p>In earlier versions of .NET, use implicit conversion of an interpolated string to a <a href="https://learn.microsoft.com/en-us/dotnet/api/system.formattablestring">System.FormattableString</a> instance and call its <a href="https://learn.microsoft.com/en-us/dotnet/api/system.formattablestring.tostring#system-formattablestring-tostring(system-iformatprovider)">ToString(IFormatProvider)</a> method to create a culture-specific result string. The following example shows how to do that:</p><pre>var cultures = new System.Globalization.CultureInfo[]<br>{<br>    System.Globalization.CultureInfo.GetCultureInfo(&quot;en-US&quot;),<br>    System.Globalization.CultureInfo.GetCultureInfo(&quot;en-GB&quot;),<br>    System.Globalization.CultureInfo.GetCultureInfo(&quot;nl-NL&quot;),<br>    System.Globalization.CultureInfo.InvariantCulture<br>};<br>var date = DateTime.Now;<br>var number = 31_415_926.536;<br>FormattableString message = $&quot;{date,23}{number,20:N3}&quot;;<br>foreach (var culture in cultures)<br>{<br>    var cultureSpecificMessage = message.ToString(culture);<br>    Console.WriteLine($&quot;{culture.Name,-10}{cultureSpecificMessage}&quot;);<br>}<br>// Output is similar to:<br>// en-US       8/27/2023 12:35:31 PM      31,415,926.536<br>// en-GB         27/08/2023 12:35:31      31,415,926.536<br>// nl-NL         27-08-2023 12:35:31      31.415.926,536<br>//               08/27/2023 12:35:31      31,415,926.536</pre><p>As the example shows, you can use one <a href="https://learn.microsoft.com/en-us/dotnet/api/system.formattablestring">FormattableString</a> instance to generate multiple result strings for various cultures.</p><h3>How to create a result string using the invariant culture</h3><p>Beginning with .NET 6, use the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.string.create#system-string-create(system-iformatprovider-system-runtime-compilerservices-defaultinterpolatedstringhandler@)">String.Create(IFormatProvider, DefaultInterpolatedStringHandler)</a> method to resolve an interpolated string to a result string for the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.globalization.cultureinfo.invariantculture#system-globalization-cultureinfo-invariantculture">InvariantCulture</a>, as the following example shows:</p><pre>string message = string.Create(CultureInfo.InvariantCulture, $&quot;Date and time in invariant culture: {DateTime.Now}&quot;);<br>Console.WriteLine(message);<br>// Output is similar to:<br>// Date and time in invariant culture: 05/17/2018 15:46:24</pre><p>In earlier versions of .NET, along with the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.formattablestring.tostring#system-formattablestring-tostring(system-iformatprovider)">FormattableString.ToString(IFormatProvider)</a> method, you can use the static <a href="https://learn.microsoft.com/en-us/dotnet/api/system.formattablestring.invariant">FormattableString.Invariant</a> method, as the following example shows:</p><pre>string message = FormattableString.Invariant($&quot;Date and time in invariant culture: {DateTime.Now}&quot;);<br>Console.WriteLine(message);<br>// Output is similar to:<br>// Date and time in invariant culture: 05/17/2018 15:46:24</pre><h3>Verbatim Strings</h3><p>In came Verbatim strings. This allowed you to have line breaks and look simpler:</p><pre>text = @&quot;This is a verbatim string.<br><br>This means you can have line breaks <br>and use double &quot;&quot;&#39;s to output quotes.&quot;;</pre><p>While many things didn’t need to be escaped, you still needed something special for double-quotes. If you needed double-quotes you had to double them to get:</p><pre>This is a verbatim string.<br><br>This means you can have line breaks<br>and use double &quot;&#39;s to output quotes.</pre><p>Not perfect, but worked in a lot of situations, but if you wanted to use a format like XML or JSON, it ended up with this ugliness:</p><pre>text = @<br>{<br>  &quot;&quot;name&quot;&quot;: &quot;&quot;Shawn&quot;<br>}<br>&quot;;</pre><h3>Verbatim Strings with Interpolation</h3><p>But you could mix verbatim and interpolation:</p><pre>text = $@&quot;This is a verbatim <br>interpolated string: {someName}&quot;;</pre><p>This worked, unless you needed brackets as text:</p><pre>// Doesn&#39;t work, as it thinks that the whole thing is interpolated<br>text = $@&quot;<br>{ <br>  &quot;&quot;name&quot;&quot;: &quot;&quot;{someName}&quot;&quot; <br>}&quot;;</pre><p>So, now we need to double-quote as well as double curly-brace:</p><pre>// Works<br>text = $@&quot;<br>{{ <br>  &quot;&quot;name&quot;&quot;: &quot;&quot;{someName}&quot;&quot; <br>}}&quot;;</pre><p>Hrmph…</p><h3>Ok, Raw String Literals?</h3><p>Here’s where Raw String Literals come in. The idea is to allow anything between a set of delimiters. That delimiter is a triple-quote (yes, seriously, but it does make sense).</p><p>When you triple-quote, everything is a literal, No magic here:</p><pre>text = &quot;&quot;&quot;This is pure text, which includes &quot; and &#39; and other literals&quot;&quot;&quot;;</pre><p>This works, but the rules are a tad different for multi-line, in that case the triple-quotes must be on their own lines:</p><pre>text = &quot;&quot;&quot;<br>Everything between the quotes is literally interpreted, <br>There is no need for escaping of anything.<br><br>Really!<br>  You can use &quot;Whatever you Like&quot;<br>&quot;&quot;&quot;;</pre><p>What’s important here is that the triple-quoted lines are not included in the string. The string starts on the first line after the triple-quote. This solves a lot of the messiness with commonly used things like JSON:</p><pre>text = &quot;&quot;&quot;<br>{<br>  &quot;name&quot;: &quot;Shawn&quot;<br>}<br>&quot;&quot;&quot;;</pre><p>Whew, that’s easy…almost.</p><h3>Interpolated Raw String Literals?</h3><p>If you add interpolation to a raw string, you find an odd situation where the compiler must know what is an interpolated section (Raw String Literals assume <em>everything</em> is just text). Like the other types of strings, you start interpolated strings with a dollar sign:</p><pre>text = $&quot;&quot;&quot;&lt;name&gt;{someName}&lt;/name&gt;&quot;&quot;&quot;;</pre><p>Simple, sure. But what if you need brackets?</p><pre>// Doesn&#39;t work, as it&#39;s expecting the brace<br>// to be part of the interpolation<br>text = $&quot;&quot;&quot; <br>{<br>  &quot;name&quot;: &quot;{someName}&quot;<br>}<br>&quot;&quot;&quot;;</pre><p>The solution? To do interpolation with brackets, the number of dollar-signs represents the number of brackets to indicate an interpolation:</p><pre>// Add number of $ for the depth of the braces needed<br>text = $$&quot;&quot;&quot;<br>{<br>  &quot;name&quot;: &quot;{{someName}}&quot;<br>}<br>&quot;&quot;&quot;;</pre><p>This isn’t a typo, this is valid C# 11. Solves a ton of situations, but still requires you to remember some stuff (I actually wish that had used the back-tick like JavaScript as it reads easier IMO). Raw string literals can also be combined with <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated#interpolated-raw-string-literals">interpolated strings</a> to embed the { and } characters in the output string. You use multiple $ characters in an interpolated raw string literal to embed { and } characters in the output string without escaping them.</p><p>You may need to create a raw string literal that has three or more consecutive double-quote characters. Raw string literals can start and end with a sequence of at least three double-quote characters. When your string literal contains three consecutive double-quotes, you start and end the raw string literal with four double quote characters:</p><pre>var moreQuotes = &quot;&quot;&quot;&quot; As you can see,&quot;&quot;&quot;Raw string literals&quot;&quot;&quot; can start and end with more than three double-quotes when needed.&quot;&quot;&quot;&quot;;</pre><p>Output:</p><pre>As you can see,&quot;&quot;&quot;Raw string literals&quot;&quot;&quot; can start and end with more than three double-quotes when needed.</pre><p>If you need to start or end a raw string literal with quote characters, use the multi-line format:</p><pre>var MultiLineQuotes = &quot;&quot;&quot;&quot;<br>               &quot;&quot;&quot;Raw string literals&quot;&quot;&quot; can start and end with more than three double-quotes when needed.<br>               &quot;&quot;&quot;&quot;;</pre><p>Output:</p><pre>&quot;&quot;&quot;Raw string literals&quot;&quot;&quot; can start and end with more than three double-quotes when needed.</pre><p>What do you think of new new syntax (and do you think you’ll be using it?) Tell me in the comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2acaa250934" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Visual Studio 2022: Customize Roslyn analyzer rules]]></title>
            <link>https://medium.com/@raindefiance/visual-studio-2022-customize-roslyn-analyzer-rules-4a1fef60f600?source=rss-f5955b00edc6------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a1fef60f600</guid>
            <category><![CDATA[roslyn]]></category>
            <category><![CDATA[visual-studio]]></category>
            <dc:creator><![CDATA[Tech Beast]]></dc:creator>
            <pubDate>Sun, 13 Oct 2024 23:49:21 GMT</pubDate>
            <atom:updated>2024-10-14T00:49:52.840Z</atom:updated>
            <content:encoded><![CDATA[<p>Each Roslyn analyzer rule, or <em>diagnostic</em>, has a default severity and suppression state that you can customize for your project. This article covers setting analyzer severities and suppressing analyzer violations.</p><h3>Severity levels</h3><p>In Visual Studio 2019 version 16.3 and later, you can configure the severity of analyzer rules in an <a href="https://learn.microsoft.com/en-us/visualstudio/code-quality/use-roslyn-analyzers?view=vs-2022#set-rule-severity-in-an-editorconfig-file">EditorConfig file</a>, from the <a href="https://learn.microsoft.com/en-us/visualstudio/code-quality/use-roslyn-analyzers?view=vs-2022#set-rule-severity-from-the-light-bulb-menu">light bulb menu</a>, and from the Error List window.</p><p>The following table shows the different severity options that you can configure for a diagnostic:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*LPFwrrylp6u579pasJT2Jg.png" /></figure><h3>View rule violations</h3><p>If an analyzer finds any analyzer rule violations, it reports them in the Error List window and in the code editor.</p><p>The following screenshot shows rule violations reported in the Error List window. The analyzer violations reported in the error list match the <a href="https://learn.microsoft.com/en-us/visualstudio/code-quality/use-roslyn-analyzers?view=vs-2022#configure-severity-levels">severity level setting</a> of the rule:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Skhv0BROravn24Ws" /></figure><p>The analyzer rule violations also appear in the code editor as squiggle lines under the offending code. For example, the following screenshot shows three violations: one error (red squiggle line), one warning (green squiggle line), and one suggestion (three gray dots):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/0*y5u24SmjZzGZrylh" /></figure><p>Many diagnostics have one or more associated <em>code fixes</em> that you can apply to correct the rule violation. Code fixes are shown in the light bulb icon menu along with other types of <a href="https://learn.microsoft.com/en-us/visualstudio/ide/quick-actions?view=vs-2022">Quick Actions</a>. For more information about code fixes, see <a href="https://learn.microsoft.com/en-us/visualstudio/ide/quick-actions?view=vs-2022">Common Quick Actions</a>.</p><h3>Configure severity levels</h3><p>You can set the rule severity using any of the following methods:</p><ul><li><a href="https://learn.microsoft.com/en-us/visualstudio/code-quality/use-roslyn-analyzers?view=vs-2022#set-rule-severity-in-an-editorconfig-file">EditorConfig</a></li><li><a href="https://learn.microsoft.com/en-us/visualstudio/code-quality/use-roslyn-analyzers?view=vs-2022#set-rule-severity-from-the-light-bulb-menu">Light bulb menu</a></li><li><a href="https://learn.microsoft.com/en-us/visualstudio/code-quality/use-roslyn-analyzers?view=vs-2022#set-rule-severity-from-the-error-list-window">Error List window</a></li><li><a href="https://learn.microsoft.com/en-us/visualstudio/code-quality/use-roslyn-analyzers?view=vs-2022#set-rule-severity-from-solution-explorer">Solution Explorer</a></li></ul><h3>Silent vs. None severity</h3><p>Silent severity rules that are enabled by default differ from disabled or None severity rules:</p><ul><li>If a code fix is registered for a Silent severity rule, Visual Studio offers the code fix as a light bulb code-refactoring action even if the hidden diagnostic isn&#39;t visible to the user. If the severity rule is disabled as None, the code fix isn&#39;t offered.</li><li>Entries that <a href="https://learn.microsoft.com/en-us/visualstudio/code-quality/use-roslyn-analyzers?view=vs-2022#set-the-severity-of-multiple-analyzer-rules-at-once-in-an-editorconfig-file">set the severity of multiple analyzer rules at once in an EditorConfig file</a> can bulk configure Silent severity rules. None severity rules can&#39;t be configured this way. Instead, they must be configured through entries that <a href="https://learn.microsoft.com/en-us/visualstudio/code-quality/use-roslyn-analyzers?view=vs-2022#set-rule-severity-in-an-editorconfig-file">set the severity in an EditorConfig file for each rule ID</a>.</li></ul><h3>Set rule severity in an EditorConfig file</h3><p>EditorConfig files are available in Visual Studio 2019 version 16.3 and later.</p><p>Setting a rule’s severity in an EditorConfig file takes precedence over any severity set in a rule set or in Solution Explorer. You can configure severity either <a href="https://learn.microsoft.com/en-us/visualstudio/code-quality/use-roslyn-analyzers?view=vs-2022#manually-configure-rule-severity-in-an-editorconfig-file">manually</a> in an EditorConfig file or <a href="https://learn.microsoft.com/en-us/visualstudio/code-quality/use-roslyn-analyzers?view=vs-2022#set-rule-severity-from-the-light-bulb-menu">automatically</a> through the light bulb that appears next to a violation.</p><h4>Manually configure rule severity in an EditorConfig file</h4><p>To configure rule severity, follow these steps:</p><ol><li><a href="https://learn.microsoft.com/en-us/visualstudio/ide/create-portable-custom-editor-options?view=vs-2022#add-an-editorconfig-file-to-a-project">Add an EditorConfig file to your project</a>, if you don’t already have one.</li><li>Add an entry for each rule you want to configure under the corresponding file extension.</li></ol><p>For example, the entry to set the severity for <a href="https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1822">CA1822</a> to error for C# files is as follows:</p><pre>[*.cs]<br>dotnet_diagnostic.CA1822.severity = error</pre><p>3. You can set the rule severity for each diagnostic rule ID in an EditorConfig file with the following syntax</p><pre>[*.cs]<br>dotnet_diagnostic.&lt;rule ID&gt;.severity = &lt;severity&gt;</pre><p>4. For IDE code-style analyzers, you can also configure them in an EditorConfig file by using a different syntax.</p><p>For example, dotnet_style_qualification_for_field = false:suggestion. However, if you set a severity using the dotnet_diagnostic syntax, it takes precedence. For more information, see <a href="https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/language-rules">Language conventions for EditorConfig</a>.</p><h4>Set the severity of multiple analyzer rules at once in an EditorConfig file</h4><p>The ability to set multiple analyzer rules at once in an EditorConfig file is available in Visual Studio 2019 version 16.5 and later.</p><p>You can set the severity for a specific category of analyzer rules or for all analyzer rules with a single entry in an EditorConfig file:</p><ul><li>Set the rule severity for a category of analyzer rules:</li></ul><p>dotnet_analyzer_diagnostic.category-&lt;rule category&gt;.severity = &lt;severity&gt;</p><ul><li>Set the rule severity for all analyzer rules:</li></ul><p>dotnet_analyzer_diagnostic.severity = &lt;severity&gt;</p><p>Entries that configure multiple analyzer rules at once apply only to rules that are <em>enabled by default</em>. Analyzer rules that are marked as disabled by default in the analyzer package must be enabled through explicit dotnet_diagnostic.&lt;rule ID&gt;.severity = &lt;severity&gt; entries.</p><p>If you have multiple entries that are applicable to a specific rule ID, the order of precedence for the applicable entry is as follows:</p><ul><li>A severity entry for an individual rule by ID takes precedence over a severity entry for a category.</li><li>A severity entry for a category takes precedence over a severity entry for all analyzer rules.</li></ul><p>Consider the following EditorConfig example, where <a href="https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1822">CA1822</a> is a performance rule:</p><pre>[*.cs]<br>dotnet_diagnostic.CA1822.severity = error<br>dotnet_analyzer_diagnostic.category-performance.severity = warning<br>dotnet_analyzer_diagnostic.severity = suggestion</pre><p>In this example, all three entries apply to the performance rule CA1822. However, using the specified precedence rules, the first rule ID-based severity entry takes precedence over the next entries. In this example, CA1822 has an effective severity of error. The remaining performance rules have a severity of warning. The analyzer rules that aren&#39;t performance rules have a severity of suggestion.</p><h3>Set rule severity from the light bulb menu</h3><p>Visual Studio provides a convenient way to configure a rule’s severity from the <a href="https://learn.microsoft.com/en-us/visualstudio/ide/quick-actions?view=vs-2022">Quick Actions</a> light bulb menu. Follow these steps:</p><ol><li>After a violation occurs, hover over the violation squiggle line in the editor and choose Show potential fixes to open the light bulb menu. Or, place your cursor on the line and press Ctrl+. (period).</li><li>From the light bulb menu, hover over a severity level for a preview of the change, and then configure the severity according to the following options:</li></ol><ul><li>Configure &lt;rule ID&gt; severity. Set the <a href="https://learn.microsoft.com/en-us/visualstudio/code-quality/use-roslyn-analyzers?view=vs-2022#configure-severity-levels">severity</a> for the specific rule.</li><li>Configure severity for all &lt;style&gt; analyzers. Set the severity for all rules in the specific <a href="https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/categories">rule category</a>.</li><li>Configure severity for all analyzers. Set the severity for all categories of analyzer rules.</li></ul><p>In the following example, select Suppress or configure issues &gt; Configure &lt;rule ID&gt; severity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/0*fE-YfYKO0SJFhPok" /></figure><p>3. Choose one of the severity options.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4PWrixdnUBqVHqeM" /></figure><p>Visual Studio adds an entry to the EditorConfig file to configure the rule to the requested severity level, as shown in the preview box.</p><p>If you don’t already have an EditorConfig file in the project, Visual Studio creates one for you.</p><h3>Set rule severity from the Error List window</h3><p>Visual Studio also provides a convenient way to configure a rule’s severity from the error list context menu. Follow these steps:</p><ol><li>After a violation occurs, right-click the diagnostic entry in the error list.</li><li>From the context menu, select Set severity, and then select one of the severity options.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9FoYl2kpS1-NYF1P" /></figure><p>Visual Studio adds an entry to the EditorConfig file to configure the rule to the requested level.</p><p>If you don’t already have an EditorConfig file in the project, Visual Studio creates one for you.</p><h3>Set rule severity from Solution Explorer</h3><p>To set rule severity from Solution Explorer, follow these steps:</p><ol><li>In Solution Explorer, expand References &gt; Analyzers (or Dependencies &gt; Analyzers for .NET Core projects).</li><li>Expand the assembly that contains the rule you want to set the severity for.</li><li>Right-click the rule and select Set severity. In the context menu, choose one of the severity options.</li></ol><p>Visual Studio adds an entry to the EditorConfig file to configure the rule to the requested level. If your project uses a rule set file instead of an EditorConfig file, the severity entry is added to the rule set file.</p><p>If you don’t already have an EditorConfig file or rule set file in the project, Visual Studio creates a new EditorConfig file for you.</p><h3>View analyzers and diagnostics from Solution Explorer</h3><p>You can do much of the customization of analyzer diagnostics from Solution Explorer. If you <a href="https://learn.microsoft.com/en-us/visualstudio/code-quality/install-roslyn-analyzers?view=vs-2022">install an analyzer</a> as a NuGet package, an Analyzers node appears under the References node (or Dependencies node for .NET Core projects) in Solution Explorer. Follow these steps to view the analyzers and diagnostics:</p><ol><li>In Solution Explorer, expand your project, expand References or Dependencies, and then expand Analyzers. Expand one of the analyzer assemblies to see the diagnostics in the assembly.</li></ol><p>The icon next to each diagnostic indicates its <a href="https://learn.microsoft.com/en-us/visualstudio/code-quality/use-roslyn-analyzers?view=vs-2022#configure-severity-levels">severity level</a>:</p><ul><li>x in a circle indicates a severity of Error</li><li>! in a triangle indicates a severity of Warning</li><li>i in a solid circle indicates a severity of Suggestion</li><li>i in a dotted circle indicates a severity of Silent</li><li>Downward-pointing arrow in a solid circle indicates a severity of None</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*68NIsnYvZWlNlgtH" /></figure><p>2. To view the properties of a diagnostic, including its description and default severity, right-click the diagnostic, and then select Properties. Or, select the diagnostic, and then press Alt+Enter.</p><p>The Properties window appears.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i3zYJePdRE0wt1RY" /></figure><p>3. To view properties for code style rules (IDE prefix) in the Properties window, such as default severity, set the <a href="https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/overview#enable-on-build">EnforceCodeStyleInBuild</a> property to true.</p><p>4. For online documentation for a diagnostic, right-click the diagnostic, and then select View Help.</p><h3>Sample Editor Config</h3><pre># Rules for ConsoleApp<br># Description: Code analysis rules for ConsoleApp.csproj.<br># Code files<br>[*.{cs,vb}]<br>dotnet_diagnostic.CA1001.severity = warning<br>dotnet_diagnostic.CA1821.severity = warning<br>dotnet_diagnostic.CA2213.severity = warning<br>dotnet_diagnostic.CA2231.severity = warning</pre><h3>Dependent projects</h3><p>In a .NET Core project, if you add a reference to a project that has NuGet analyzers, Visual Studio automatically adds those analyzers to the dependent project. To disable this behavior (for example, if the dependent project is a unit test project), mark the NuGet package as private by setting the PrivateAssets attribute in the <em>.csproj</em> or <em>.vbproj</em> file of the referenced project:</p><pre>&lt;PackageReference Include=&quot;Microsoft.CodeAnalysis.NetAnalyzers&quot; Version=&quot;5.0.0&quot; PrivateAssets=&quot;all&quot; /&gt;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a1fef60f600" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ReactNode vs PropsWithChildren]]></title>
            <link>https://medium.com/@raindefiance/reactnode-vs-propswithchildren-d3f51ae35324?source=rss-f5955b00edc6------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3f51ae35324</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react-js-tutorials]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Tech Beast]]></dc:creator>
            <pubDate>Fri, 30 Aug 2024 01:11:21 GMT</pubDate>
            <atom:updated>2024-08-30T23:12:01.396Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding the children Prop in React with TypeScript</h3><p>In React development, efficiently managing props is crucial, especially when utilizing TypeScript for type safety. This post will explore the children prop—how to correctly define and use it in your React components, and the importance of using the right type definitions for your components. We will explore practical examples that illustrate these concepts, ensuring clarity and ease of understanding.</p><h3>What is the Children Prop?</h3><p>The children prop is a unique feature in React components. It allows developers to pass JSX elements as children to a component, enabling more flexible and reusable code. This capability means that any component can act as a wrapper for other components or elements, seamlessly integrating them into its layout.</p><p>However, when defining props in TypeScript, the children prop is often overlooked. This oversight can lead to errors, particularly when attempting to access children within a component without having defined it in the props type. Understanding how to properly include and type the children prop is essential for building robust React applications.</p><h3>Defining Props Without Children</h3><p>Consider a simple component that requires a title but does not use children. In such cases, you might define the props like this:</p><pre>type Props = {<br>  title: string;<br>};</pre><p>While this definition works perfectly for components that do not utilize the children prop, it becomes problematic when you attempt to access children. If you try to extract children from this props type, TypeScript will throw an error indicating that the property does not exist.</p><h3>Updating the Props Type to Include children</h3><p>To utilize the children prop, adjustments to the props type must be made. Instead of using a traditional prop like description, you can redefine your props to include children using a more appropriate setup.</p><p>The recommended type for children is ReactNode. This type is designed to encompass anything that can be rendered, including strings, numbers, and JSX elements. To implement this, you will need to import ReactNode from the appropriate types package.</p><p>It’s also a good practice to include the type ReactNode decorator in the import statement. This special decorator is useful in TypeScript projects as it signals to the build tool that this import can be removed in the final code that runs in the browser. This is important because the browser cannot process TypeScript types.</p><pre>import { type ReactNode } from &#39;react&#39;;<br><br>interface MyComponentProps {<br>  title: string;<br>  children: ReactNode;<br>}</pre><p>With ReactNode defined, you can extract and use the children prop effectively within your component.</p><h3>Alternative Approach: Using PropsWithChildren</h3><p>Another approach to manage props with the children property is to utilize the PropsWithChildren type provided by React. This generic type simplifies the definition of props that include children.</p><pre>import { PropsWithChildren } from &#39;react&#39;;<br><br>interface MyComponentProps {<br>  title: string;<br>}<br>const MyComponent: React.FC&lt;PropsWithChildren&lt;MyComponentProps&gt;&gt; <br>                                      = ({ title, children }: MyComponentProps) =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;{title}&lt;/h1&gt;<br>      &lt;div&gt;{children}&lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>Using PropsWithChildren allows you to automatically include the children prop without needing to specify it manually in the props interface.</p><h3>Comparing Both Approaches</h3><p>Choosing between defining the children prop manually or using PropsWithChildren depends on your coding style and preferences. Here’s a quick comparison:</p><ol><li><strong>Manual Definition:</strong> Offers more control over prop types but requires more lines of code.</li><li><strong>PropsWithChildren:</strong> Cleaner and easier to read, automatically includes children but might obscure the explicit definition of props.</li></ol><p>Ultimately, both methods achieve the same result. It’s up to the developer to decide which approach aligns better with their coding practices.</p><h3>Handling Optional Children</h3><p>In some cases, you may want to make the children prop optional. To do this, simply append a question mark to the children property in your props definition:</p><pre>type Props = {<br>  title: string;<br>  children?: React.ReactNode;<br>};</pre><p>This adjustment allows the component to function even if no children are provided, adding another layer of flexibility to your components.</p><h3>Conclusion</h3><p>Defining types for props with children in React is a fundamental aspect of building robust applications. Understanding how to correctly handle the children prop in React can prevent errors and enhance the overall quality of your code. By defining the type as ReactNode or using PropsWithChildren, developers can avoid errors and ensure their components function correctly when wrapped around other JSX elements. Whether you choose to define props manually or use PropsWithChildren, the key takeaway is to ensure that your components are flexible and maintainable.</p><p>By mastering these concepts, you will be better equipped to create reusable components that can adapt to various needs, ultimately leading to more efficient and effective React applications.</p><p>As you continue your journey in React development, remember to keep these principles in mind. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3f51ae35324" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>