<?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 Ajay Narkhedkar on Medium]]></title>
        <description><![CDATA[Stories by Ajay Narkhedkar on Medium]]></description>
        <link>https://medium.com/@ajax-workspace?source=rss-b9ec15fdfe93------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZMCp9jb7R_Dfv85OzxqCFA.jpeg</url>
            <title>Stories by Ajay Narkhedkar on Medium</title>
            <link>https://medium.com/@ajax-workspace?source=rss-b9ec15fdfe93------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 10:15:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ajax-workspace/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[Inside the .NET Garbage Collector: How Mark, Sweep, Compact, and Finalization Really Work in C#]]></title>
            <link>https://ajax-workspace.medium.com/inside-the-net-garbage-collector-how-mark-sweep-compact-and-finalization-really-work-in-c-44e98d59f551?source=rss-b9ec15fdfe93------2</link>
            <guid isPermaLink="false">https://medium.com/p/44e98d59f551</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[object-oriented-concepts]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[oops-concepts]]></category>
            <category><![CDATA[garbage-collection]]></category>
            <dc:creator><![CDATA[Ajay Narkhedkar]]></dc:creator>
            <pubDate>Sat, 01 Aug 2026 05:10:36 GMT</pubDate>
            <atom:updated>2026-08-01T05:10:36.547Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In the previous article, we learned how the .NET Garbage Collector (GC) organizes objects into <strong>Generation 0, Generation 1, and Generation 2</strong> to improve performance.</p><p>But another important question remains:</p><blockquote><strong><em>How does the Garbage Collector actually know which objects to remove and which ones to keep?</em></strong></blockquote><p>Does it randomly delete objects? How does it avoid deleting objects that are still in use? And what happens to memory after unused objects are removed?</p><p>The answer lies in four important phases of the .NET Garbage Collector:</p><ul><li><strong>Mark</strong></li><li><strong>Sweep</strong></li><li><strong>Compact</strong></li><li><strong>Finalization</strong></li></ul><p>These phases work together to identify unused objects, reclaim memory safely, and keep your application running efficiently.</p><p>In this article, you’ll explore each phase step by step and understand what happens behind the scenes whenever the Garbage Collector runs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t0AtRJwvMjBCUnjk0SGEgA.png" /></figure><h3>Why Does the Garbage Collector Need Multiple Phases?</h3><p>Imagine cleaning a warehouse.</p><p>Before removing anything, you first identify which items are still needed. Then you remove unwanted items. Finally, you reorganize the remaining items to free up space.</p><p>The Garbage Collector follows a similar approach.</p><p>Instead of deleting everything, it performs its work in carefully planned phases to ensure that only unused objects are removed.</p><h3>Overview of the GC Lifecycle</h3><p>Every time the Garbage Collector runs, it follows a sequence similar to this:</p><pre>Application Running<br>        │<br>        ▼<br>Memory Pressure Increases<br>        │<br>        ▼<br>Garbage Collection Starts<br>        │<br>        ▼<br>Mark Phase<br>        │<br>        ▼<br>Sweep Phase<br>        │<br>        ▼<br>Compact Phase<br>        │<br>        ▼<br>Finalization (if required)<br>        │<br>        ▼<br>Application Continues</pre><p>Each phase has a specific responsibility.</p><h4>Step 1 — Mark Phase</h4><p>The first job of the Garbage Collector is to determine which objects are still being used.</p><p>It begins by identifying <strong>GC Roots</strong>.</p><p>GC Roots are starting points that represent objects the application can still reach.</p><p>Examples include:</p><ul><li>Local variables</li><li>Static variables</li><li>Method parameters</li><li>CPU registers</li><li>Active threads</li></ul><p>Starting from these roots, the Garbage Collector follows every reference to discover all reachable objects.</p><p>Objects that can still be reached are <strong>marked as alive</strong>.</p><p>Objects that cannot be reached remain unmarked.</p><h4>Visual Flow</h4><pre>GC Roots<br>   │<br>   ├────────► Customer<br>   │              │<br>   │              ▼<br>   │           Order<br>   │              │<br>   │              ▼<br>   │          Product<br>   │<br>   └────────► Configuration</pre><pre>Invoice (No Reference)</pre><p>The Invoice object has no path from any GC Root, so it becomes a candidate for collection.</p><h4>Step 2 — Sweep Phase</h4><p>Once marking is complete, the Garbage Collector knows exactly which objects are still needed.</p><p>Now it removes the objects that were <strong>not marked</strong>.</p><p>These objects are considered unreachable because nothing in the application references them anymore.</p><p>For example:</p><pre>Managed Heap</pre><pre>Employee      ✓ Alive<br>Order         ✓ Alive<br>Customer      ✓ Alive<br>Invoice       ✗ Removed<br>Cart          ✗ Removed</pre><p>Only unreachable objects are reclaimed.</p><h4>Step 3 — Compact Phase</h4><p>After removing unused objects, empty spaces appear in memory.</p><p>If left unchanged, memory becomes fragmented.</p><p>Fragmentation means free memory is scattered into many small gaps, making future allocations less efficient.</p><p>To solve this, the Garbage Collector moves the remaining live objects together.</p><h4>Before Compaction</h4><pre>Employee<br>Empty<br>Order<br>Empty<br>Customer<br>Empty</pre><h4>After Compaction</h4><pre>Employee<br>Order<br>Customer<br>Free Memory</pre><p>The free memory becomes one large continuous block, making future object allocations faster.</p><blockquote><strong><em>Note:</em></strong><em> The .NET runtime automatically updates object references after compaction, so your code continues to work without any changes.</em></blockquote><h4>Step 4 — Finalization</h4><p>Some objects manage <strong>unmanaged resources</strong> such as:</p><ul><li>File handles</li><li>Database connections</li><li>Network sockets</li><li>Operating system resources</li></ul><p>These resources require additional cleanup before memory can be reclaimed.</p><p>If a class defines a <strong>finalizer</strong>, the Garbage Collector executes it before completely removing the object.</p><p>Example:</p><pre>class FileManager<br>{<br>    ~FileManager()<br>    {<br>        // Cleanup unmanaged resources<br>    }<br>}</pre><p>Finalizers are <strong>not executed immediately</strong> after an object becomes unreachable. The Garbage Collector decides when they run.</p><p>In modern .NET applications, IDisposable is usually the preferred approach for releasing unmanaged resources. We&#39;ll cover that in the next article.</p><h3>Complete Internal Flow</h3><pre>Object Created<br>      │<br>      ▼<br>Stored in Managed Heap<br>      │<br>      ▼<br>Application Uses Object<br>      │<br>      ▼<br>Reference Removed<br>      │<br>      ▼<br>Garbage Collector Starts<br>      │<br>      ▼<br>Mark Reachable Objects<br>      │<br>      ▼<br>Sweep Unreachable Objects<br>      │<br>      ▼<br>Compact Remaining Objects<br>      │<br>      ▼<br>Run Finalizers (if needed)<br>      │<br>      ▼<br>Memory Ready for Reuse</pre><h3>Practical Example</h3><pre>class Employee<br>{<br>    public string Name { get; set; }<br>}</pre><pre>Employee emp = new Employee();</pre><pre>emp = null;</pre><p>What happens?</p><ol><li>The Employee object becomes unreachable.</li><li>During the next GC cycle, it is not marked.</li><li>The Sweep phase reclaims its memory.</li><li>If the object had a finalizer, it would run before the object is fully reclaimed.</li><li>The remaining objects may be compacted to eliminate memory gaps.</li></ol><h3>Common Mistakes</h3><h4>Believing the Garbage Collector deletes objects immediately</h4><p>Objects are collected only when the Garbage Collector decides to run.</p><h4>Thinking null destroys an object</h4><p>Setting a variable to null removes only that reference. The object is collected later if no other references exist.</p><h4>Ignoring fragmentation</h4><p>Simply removing objects is not enough. Compaction is important because it keeps memory contiguous and efficient.</p><h4>Relying on finalizers for normal cleanup</h4><p>Finalizers run at a nondeterministic time. For most cleanup scenarios, implementing IDisposable is a better choice.</p><h3>Best Practices</h3><ul><li>Trust the .NET Garbage Collector to manage managed memory.</li><li>Avoid unnecessary object allocations in performance-critical code.</li><li>Do not force garbage collection using GC.Collect() unless there is a well-understood reason.</li><li>Implement IDisposable when working with unmanaged resources instead of relying on finalizers.</li><li>Keep object lifetimes as short as practical to reduce memory pressure.</li></ul><h3>Key Takeaways</h3><ul><li>The Garbage Collector follows a structured process rather than deleting objects randomly.</li><li>The <strong>Mark</strong> phase identifies reachable objects.</li><li>The <strong>Sweep</strong> phase removes unreachable objects.</li><li>The <strong>Compact</strong> phase eliminates memory fragmentation by moving live objects together.</li><li><strong>Finalization</strong> provides an opportunity to clean up unmanaged resources before an object is fully reclaimed.</li><li>Understanding these phases helps you write more efficient and memory-friendly .NET applications.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44e98d59f551" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Secret Behind .NET]]></title>
            <link>https://ajax-workspace.medium.com/the-secret-behind-net-c4070bf10891?source=rss-b9ec15fdfe93------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4070bf10891</guid>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[oops-concepts]]></category>
            <category><![CDATA[garbage-collection]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Ajay Narkhedkar]]></dc:creator>
            <pubDate>Thu, 23 Jul 2026 17:28:25 GMT</pubDate>
            <atom:updated>2026-07-23T17:28:25.315Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Secret Behind .NET Performance: Understanding Garbage Collection Generations (Gen 0, Gen 1 &amp; Gen 2) in C#</h3><h3>Introduction</h3><p>In the previous article, we learned that the .NET Garbage Collector (GC) automatically removes unused objects from memory. But one important question remains:</p><blockquote><strong><em>Does the Garbage Collector scan every object in memory every time it runs?</em></strong></blockquote><p>If it did, large applications with millions of objects would become slow and inefficient.</p><p>To solve this problem, .NET uses an intelligent strategy called <strong>Generational Garbage Collection</strong>. Instead of treating every object equally, the Garbage Collector groups objects based on their age. Most newly created objects are short-lived, while only a few survive for a long time.</p><p>In this article, you’ll learn what <strong>Generation 0, Generation 1, and Generation 2</strong> are, why they exist, how objects move between them, and how this design improves the performance of .NET applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6eFxkjNHMwjxWkW3KiXccg.png" /><figcaption>GC 02</figcaption></figure><h3>Why Does .NET Use Generations?</h3><p>Research shows that <strong>most objects created by an application live for only a short time</strong>.</p><p>For example:</p><ul><li>Temporary strings</li><li>API request objects</li><li>Local collections</li><li>Validation objects</li><li>Temporary DTOs</li></ul><p>These objects are often created, used, and discarded within milliseconds.</p><p>On the other hand, objects such as:</p><ul><li>Application configuration</li><li>Cached data</li><li>Singleton services</li><li>Static objects</li></ul><p>remain alive for much longer.</p><p>Instead of checking every object during every garbage collection cycle, .NET focuses on the newest objects first. This makes memory cleanup much faster.</p><h3>What Are Garbage Collection Generations?</h3><p>The managed heap is divided into three logical generations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*5ScXfZAyXXaVzdfEy_oVCw.png" /></figure><p>Think of generations as <strong>age groups</strong> rather than separate memory areas.</p><h3>How Objects Move Between Generations</h3><p>Every new object starts its journey in <strong>Generation 0</strong>.</p><p>If the object is no longer needed during a garbage collection, it is removed.</p><p>If it is still being used, it survives and moves to the next generation.</p><p>The process continues until the object eventually becomes unreachable and is collected.</p><h3>Internal Flow</h3><pre>Create Object<br>      │<br>      ▼<br>Generation 0<br>      │<br>      ├── Not Referenced<br>      │        │<br>      │        ▼<br>      │    Removed by GC<br>      │<br>      ▼<br>Still Referenced<br>      │<br>      ▼<br>Generation 1<br>      │<br>      ├── Not Referenced<br>      │        │<br>      │        ▼<br>      │    Removed by GC<br>      │<br>      ▼<br>Still Referenced<br>      │<br>      ▼<br>Generation 2<br>      │<br>      ▼<br>Removed when no longer reachable</pre><h3>Understanding Generation 0</h3><p>Generation 0 contains <strong>all newly created objects</strong>.</p><p>Example:</p><pre>Employee employee = new Employee();</pre><p>When this object is created, it is placed in <strong>Generation 0</strong>.</p><p>Generation 0 is collected most frequently because most temporary objects become unused very quickly.</p><p>Examples include:</p><ul><li>Temporary strings</li><li>Method variables</li><li>Request objects</li><li>DTOs</li><li>LINQ query results</li></ul><p>Since Gen 0 contains many short-lived objects, collections are usually fast.</p><h3>Understanding Generation 1</h3><p>Generation 1 acts as a bridge between short-lived and long-lived objects.</p><p>Objects reach Gen 1 only if they survive a Gen 0 collection.</p><p>These objects have lived longer than expected but are not yet considered long-lived.</p><p>Examples:</p><ul><li>Objects shared across multiple method calls</li><li>Frequently reused collections</li><li>Temporary cache entries</li></ul><p>Generation 1 is collected less often than Generation 0.</p><h3>Understanding Generation 2</h3><p>Generation 2 stores objects that have survived multiple garbage collections.</p><p>These objects usually remain in memory for a long time.</p><p>Examples include:</p><ul><li>Application configuration</li><li>Cached data</li><li>Singleton services</li><li>Static collections</li><li>Shared application objects</li></ul><p>Since Gen 2 often contains many important objects, collections are more expensive and happen less frequently.</p><h3>Visual Journey of an Object</h3><pre>Application Starts<br>        │<br>        ▼<br>Create Employee Object<br>        │<br>        ▼<br>Generation 0<br>        │<br>        ▼<br>Still Needed?<br>   Yes ─────────► Generation 1<br>        │<br>        ▼<br>Still Needed?<br>   Yes ─────────► Generation 2<br>        │<br>        ▼<br>Reference Removed<br>        │<br>        ▼<br>Garbage Collector Removes Object</pre><h3>Practical Example</h3><pre>class Employee<br>{<br>    public string Name { get; set; }<br>}</pre><pre>Employee employee = new Employee();<br>employee.Name = &quot;Ajay&quot;;</pre><p>Initially:</p><pre>Generation 0</pre><p>Suppose the object is still needed after the first garbage collection.</p><p>It moves to:</p><pre>Generation 1</pre><p>If it continues to be referenced for a longer period, it is promoted again.</p><pre>Generation 2</pre><p>Eventually:</p><pre>employee = null;</pre><p>Once no references remain, the Garbage Collector removes the object during an appropriate collection cycle.</p><h3>What About the Large Object Heap (LOH)?</h3><p>Most objects are stored in the normal managed heap.</p><p>However, very large objects (typically <strong>85 KB or larger</strong>) are allocated in a separate area called the <strong>Large Object Heap (LOH)</strong>.</p><p>Examples include:</p><ul><li>Large byte arrays</li><li>Large image buffers</li><li>Large collections</li></ul><p>The LOH is managed differently because moving very large objects frequently would reduce performance.</p><blockquote><em>We’ll explore the Large Object Heap and its performance considerations in more detail in a later article.</em></blockquote><h3>Common Mistakes</h3><h4>Thinking objects are manually assigned to generations</h4><p>Developers never choose the generation. The .NET runtime automatically manages object promotion.</p><h4>Assuming Generation 2 is “better”</h4><p>Generation 2 simply means an object has lived longer. It does not indicate higher importance or better performance.</p><h4>Believing all generations are collected together</h4><p>Most garbage collection cycles target only Generation 0. Gen 1 and Gen 2 are collected less frequently to improve performance.</p><h4>Assuming promotion happens immediately</h4><p>Objects move to a higher generation only after surviving a garbage collection.</p><h3>Best Practices</h3><ul><li>Allow the Garbage Collector to manage object generations automatically.</li><li>Avoid creating unnecessary temporary objects in performance-critical code.</li><li>Reuse objects where appropriate to reduce allocation pressure.</li><li>Don’t force collections using GC.Collect() unless there is a specific, well-understood reason.</li><li>Focus on writing clean, maintainable code rather than trying to manipulate generations.</li></ul><h3>Key Takeaways</h3><ul><li>Every new object starts in <strong>Generation 0</strong>.</li><li>Objects that survive a collection are promoted to higher generations.</li><li><strong>Generation 0</strong> is collected most frequently.</li><li><strong>Generation 2</strong> contains long-lived objects and is collected less often.</li><li>The generational design significantly improves the performance of .NET applications by avoiding unnecessary scans of long-lived objects.</li><li>Developers do not manually control object generations; the CLR manages the entire lifecycle.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4070bf10891" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Garbage Collection in C#: How .NET Automatically Manages Memory]]></title>
            <link>https://ajax-workspace.medium.com/garbage-collection-in-c-how-net-automatically-manages-memory-88c8aa449387?source=rss-b9ec15fdfe93------2</link>
            <guid isPermaLink="false">https://medium.com/p/88c8aa449387</guid>
            <category><![CDATA[garbage-collection]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[class]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[oops-concepts]]></category>
            <dc:creator><![CDATA[Ajay Narkhedkar]]></dc:creator>
            <pubDate>Thu, 23 Jul 2026 17:14:48 GMT</pubDate>
            <atom:updated>2026-07-23T17:14:48.338Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Have you ever wondered what happens to an object after your C# application no longer uses it? Does it remain in memory forever? If so, wouldn’t your application eventually run out of memory?</p><p>Managing memory manually is one of the biggest challenges in software development. Languages like C and C++ require developers to allocate and release memory themselves, and forgetting to free memory can lead to memory leaks and application crashes.</p><p>Fortunately, C# solves this problem using <strong>Garbage Collection (GC)</strong>. The .NET runtime automatically identifies and removes unused objects, helping developers focus on building applications instead of manually managing memory.</p><p>In this article, you’ll learn what Garbage Collection is, why it’s needed, how it works at a high level, and how it helps keep .NET applications efficient and reliable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zs6z2d1x8ARtCW_7LeBN5g.png" /><figcaption>GC</figcaption></figure><h3>What is Garbage Collection?</h3><p><strong>Garbage Collection (GC)</strong> is an automatic memory management feature provided by the .NET runtime.</p><p>Its primary responsibility is to:</p><ul><li>Allocate memory for new objects.</li><li>Track objects that are still in use.</li><li>Identify objects that are no longer reachable.</li><li>Reclaim the memory occupied by unused objects.</li></ul><p>In simple terms, Garbage Collection acts like an automatic housekeeping service for your application’s memory.</p><blockquote><strong><em>Definition:</em></strong><em> Garbage Collection is the process of automatically removing objects from memory when they are no longer used by the application.</em></blockquote><h3>Why Do We Need Garbage Collection?</h3><p>Every application creates objects while it runs. These objects consume memory.</p><p>Imagine an e-commerce application that creates:</p><ul><li>Customer objects</li><li>Product objects</li><li>Shopping carts</li><li>Orders</li><li>Payment details</li></ul><p>Some of these objects are needed only for a short period. If they remain in memory after their work is complete, the application gradually consumes more memory, leading to poor performance or even crashes.</p><p>Without Garbage Collection, developers would have to manually free memory after every object is no longer needed. This process is time-consuming and error-prone.</p><p>Garbage Collection eliminates this burden by automatically reclaiming unused memory.</p><h3>Managed Memory vs Manual Memory Management</h3><p>Understanding the difference helps explain why Garbage Collection is so valuable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*AbtOtIyElr-kJD-n4y4uSA.png" /></figure><p>Because C# uses <strong>managed memory</strong>, developers spend less time worrying about memory cleanup and more time writing business logic.</p><h3>Where Are Objects Stored?</h3><p>When you create an object using the new keyword, the .NET runtime allocates memory for that object in the <strong>Managed Heap</strong>.</p><p>For example:</p><pre>Employee employee = new Employee();</pre><p>Here:</p><ul><li>The Employee object is created in the <strong>Managed Heap</strong>.</li><li>The employee variable holds a reference to that object.</li></ul><p>As your application runs, many objects are created in the managed heap. Some remain active, while others become unused.</p><p>This is where the Garbage Collector comes into action.</p><h3>How Does Garbage Collection Work?</h3><p>The Garbage Collector continuously keeps track of objects in the managed heap.</p><p>When memory becomes limited or the runtime determines that cleanup is beneficial, the Garbage Collector starts its work.</p><p>At a high level, it performs the following steps:</p><ol><li>Checks which objects are still being used.</li><li>Identifies objects that are no longer reachable.</li><li>Removes unused objects from memory.</li><li>Reclaims the freed memory for future object allocations.</li></ol><p>The entire process is automatic and managed by the Common Language Runtime (CLR).</p><h3>Internal Flow of Garbage Collection</h3><p>The following simplified flow shows what happens when your application creates and releases objects.</p><pre>Application Starts<br>        │<br>        ▼<br>Create Objects (new)<br>        │<br>        ▼<br>Objects Stored in Managed Heap<br>        │<br>        ▼<br>Application Continues Running<br>        │<br>        ▼<br>Some Objects Become Unused<br>        │<br>        ▼<br>Garbage Collector Starts<br>        │<br>        ▼<br>Finds Reachable Objects<br>        │<br>        ▼<br>Identifies Unused Objects<br>        │<br>        ▼<br>Removes Unused Objects<br>        │<br>        ▼<br>Memory Becomes Available Again</pre><p>This automatic process happens behind the scenes without requiring developer intervention.</p><h3>A Quick Note on Generations</h3><p>The .NET Garbage Collector organizes objects into <strong>Generations</strong> to improve performance.</p><p>There are three generations:</p><ul><li><strong>Generation 0</strong></li><li><strong>Generation 1</strong></li><li><strong>Generation 2</strong></li></ul><p>New objects are initially created in <strong>Generation 0</strong>. If they survive a collection, they may be promoted to higher generations.</p><p>You don’t need to understand the details yet. We’ll explore how generations work in the next article.</p><h3>Practical Example</h3><p>Consider a simple console application.</p><pre>class Employee<br>{<br>    public string Name { get; set; }<br>}</pre><pre>Employee employee = new Employee();<br>employee.Name = &quot;Ajay&quot;;</pre><p>The Employee object is created and stored in the managed heap.</p><p>Later in the program:</p><pre>employee = null;</pre><p>Now the object no longer has any reference pointing to it.</p><p>At some point, the Garbage Collector detects that the object is unreachable and removes it from memory automatically.</p><p>You never have to explicitly free its memory.</p><h3>Real-World Analogy</h3><p>Think of a hotel.</p><ul><li>Guests represent application objects.</li><li>Rooms represent memory.</li><li>Guests check in and use rooms.</li><li>After guests leave, the rooms become empty.</li><li>Housekeeping cleans the rooms so new guests can use them.</li></ul><p>Similarly:</p><ul><li>Your application creates objects.</li><li>Objects are used while needed.</li><li>Once they are no longer referenced, the Garbage Collector cleans them up.</li><li>The reclaimed memory is ready for future objects.</li></ul><h3>Benefits of Garbage Collection</h3><p>Garbage Collection provides several advantages:</p><ul><li>Automatic memory management.</li><li>Reduces memory leaks caused by forgotten cleanup.</li><li>Improves application reliability.</li><li>Allows developers to focus on business logic.</li><li>Optimizes memory usage by reusing available memory.</li><li>Simplifies application development.</li></ul><p>These benefits make .NET applications easier to build and maintain compared to environments requiring manual memory management.</p><h3>Common Mistakes</h3><h3>Assuming objects are deleted immediately</h3><p>Setting a variable to null does <strong>not</strong> instantly remove the object from memory. It only removes one reference to the object. The Garbage Collector decides when to reclaim the memory.</p><h3>Calling GC.Collect() unnecessarily</h3><p>Many beginners believe calling GC.Collect() frequently improves performance.</p><p>In reality, forcing garbage collection often <strong>reduces performance</strong> because the .NET runtime already determines the optimal time to perform collections.</p><h3>Confusing object lifetime with variable scope</h3><p>A variable going out of scope doesn’t always mean the object is immediately collected. As long as the object remains reachable, it stays in memory.</p><h3>Ignoring object references</h3><p>If an object is still referenced — even unintentionally — the Garbage Collector cannot remove it. Unused references can keep objects alive longer than expected.</p><h3>Best Practices</h3><ul><li>Trust the .NET Garbage Collector to manage memory automatically.</li><li>Create objects only when necessary.</li><li>Remove unnecessary references to objects you no longer need.</li><li>Avoid forcing garbage collection with GC.Collect() unless there&#39;s a well-understood, specialized reason.</li><li>Design applications to minimize unnecessary object allocations in performance-critical code.</li></ul><h3>Key Takeaways</h3><ul><li>Garbage Collection is the automatic memory management system in .NET.</li><li>Objects created with the new keyword are stored in the managed heap.</li><li>The Garbage Collector identifies and removes objects that are no longer reachable.</li><li>Developers do not need to manually free managed memory.</li><li>Automatic memory management reduces memory leaks and improves application reliability.</li><li>Understanding Garbage Collection is essential for writing efficient, high-performance C# applications.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88c8aa449387" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Confusing Value Types and Reference Types in C#: Learn It Once and Never Forget It]]></title>
            <link>https://ajax-workspace.medium.com/stop-confusing-value-types-and-reference-types-in-c-learn-it-once-and-never-forget-it-f2b4bcb79bb9?source=rss-b9ec15fdfe93------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2b4bcb79bb9</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[class]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Ajay Narkhedkar]]></dc:creator>
            <pubDate>Sun, 19 Jul 2026 17:38:05 GMT</pubDate>
            <atom:updated>2026-07-19T17:38:05.485Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>One of the most important concepts every C# developer should understand is the difference between <strong>Value Types</strong> and <strong>Reference Types</strong>. This concept affects how data is stored, copied, passed to methods, and managed in memory.</p><p>Many beginners become confused when they assign one variable to another. Sometimes changing one variable does not affect the other, while other times both variables seem to change together. The reason lies in whether the type is a <strong>Value Type</strong> or a <strong>Reference Type</strong>.</p><p>In this article, you’ll learn what these two categories are, why C# uses them, how they work internally, and when each behaves differently through practical examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xacMJhegLzPqGGRi2CMglw.png" /><figcaption>What is Value Type and Referance Type</figcaption></figure><h3>What are Value Types?</h3><p>A <strong>Value Type</strong> stores the actual data directly inside the variable.</p><p>Each variable owns its own copy of the data. If you copy a value type variable, a completely new copy of the data is created.</p><p>Common value types include:</p><ul><li>int</li><li>double</li><li>float</li><li>char</li><li>bool</li><li>decimal</li><li>DateTime</li><li>struct</li><li>enum</li></ul><h3>Example</h3><pre>int x = 10;<br>int y = x;<br>y = 20;<br>Console.WriteLine(x); // 10<br>Console.WriteLine(y); // 20</pre><p>Although y was copied from x, changing y does not affect x because both variables have independent copies.</p><h3>What are Reference Types?</h3><p>A <strong>Reference Type</strong> stores the <strong>memory address</strong> (reference) of an object rather than the object itself.</p><p>The actual object is stored elsewhere in memory, and multiple variables can point to the same object.</p><p>Common reference types include:</p><ul><li>class</li><li>string</li><li>array</li><li>delegate</li><li>interface</li><li>object</li></ul><h3>Example</h3><pre>class Employee<br>{<br>    public string Name { get; set; }<br>}</pre><pre>Employee emp1 = new Employee();<br>emp1.Name = &quot;Ajay&quot;;<br>Employee emp2 = emp1;<br>emp2.Name = &quot;Rahul&quot;;<br>Console.WriteLine(emp1.Name); // Rahul<br>Console.WriteLine(emp2.Name); // Rahul</pre><p>Here, both variables refer to the same object. Updating the object through one variable is visible through the other.</p><h3>Why Do We Need Two Different Type Categories?</h3><p>Different kinds of data have different requirements.</p><p>Small pieces of data such as numbers and Boolean values are efficient to copy directly.</p><p>Larger or more complex objects, such as employees, customers, or orders, would be expensive to duplicate every time they are assigned. Instead, C# copies only the reference, making object handling more efficient.</p><p>This design improves both performance and memory usage.</p><h3>How Does It Work?</h3><p>When you assign one variable to another:</p><p>Value TypeReference TypeCopies the actual valueCopies the memory referenceTwo independent variablesTwo variables share one objectChanges do not affect the originalChanges affect both variables</p><h3>Internal Memory Flow</h3><p>Although the actual implementation is handled by the .NET runtime, a simplified view helps understand the behavior.</p><h3>Value Type</h3><pre>Stack<br><br>number1 = 100<br>number2 = 100</pre><p>Each variable stores its own value.</p><p>Changing one variable does not affect the other.</p><h3>Reference Type</h3><pre>Stack                  Heap<br>person1 -----------\<br>                     -----&gt; Employee Object<br>person2 -----------/         Name = &quot;Ajay&quot;</pre><p>Both variables point to the same object.</p><p>Changing the object through one reference changes what both variables see.</p><blockquote><strong><em>Note:</em></strong><em> A common rule of thumb is that value types are often stored inline (commonly on the stack for local variables), while reference type objects are allocated on the heap. In practice, the exact storage depends on context, and the .NET runtime decides the memory layout.</em></blockquote><h3>Assignment Flow</h3><h3>Value Type</h3><pre>x = 10<br>Copy<br>x ─────► y<br>x = 10<br>y = 10</pre><p>After copying:</p><pre>Change y = 20<br>x = 10<br>y = 20</pre><p>Both variables are independent.</p><h3>Reference Type</h3><pre>emp1<br><br>Copy Reference<br>emp1 ─────► Employee Object<br>emp2 ─────┘</pre><p>After:</p><pre>emp2.Name = &quot;Rahul</pre><p>The object itself changes.</p><p>Both variables now see:</p><pre>Name = Rahul</pre><h3>Passing to Methods</h3><p>The same behavior appears when passing variables to methods.</p><h3>Value Type Example</h3><pre>void Update(int number)<br>{<br>    number = 100;<br>}<br><br>int value = 10;<br>Update(value);<br>Console.WriteLine(value);</pre><p>Output:</p><pre>10</pre><p>The method receives a copy of the value.</p><h3>Reference Type Example</h3><pre>class Student<br>{<br>    public string Name { get; set; }<br>}<br><br>void Update(Student student)<br>{<br>    student.Name = &quot;John&quot;;<br>}<br>Student s = new Student();<br>s.Name = &quot;Ajay&quot;;<br>Update(s);<br>Console.WriteLine(s.Name);</pre><p>Output:</p><pre>John</pre><p>The method receives a copy of the reference, so both the caller and the method refer to the same object.</p><h3>Practical Example</h3><p>Imagine an online shopping application.</p><h3>Value Type</h3><pre>int quantity = 5;</pre><p>Each order should have its own quantity value.</p><p>Copying the quantity is simple and inexpensive.</p><h3>Reference Type</h3><pre>Order order = new Order();</pre><p>An order contains many pieces of information:</p><ul><li>Customer</li><li>Products</li><li>Address</li><li>Payment</li><li>Status</li></ul><p>Instead of copying the entire order object every time, C# copies only its reference.</p><h3>Common Mistakes</h3><h4>Assuming all variables behave the same</h4><p>Value types and reference types follow different assignment rules.</p><h4>Expecting a copied object to be independent</h4><p>Assigning one object variable to another does <strong>not</strong> create a new object.</p><h4>Confusing object modification with variable reassignment</h4><p>Changing an object’s properties affects all references to that object. Reassigning a reference variable to a new object does not change other variables that still point to the original object.</p><h4>Believing everything is stored only on the Stack or Heap</h4><p>Memory management in .NET is more sophisticated than a simple “stack vs heap” rule. Focus on understanding value-copy versus reference-copy behavior first.</p><h3>Best Practices</h3><ul><li>Use value types for small, independent pieces of data.</li><li>Use classes (reference types) for entities that represent real-world objects.</li><li>Understand assignment behavior before modifying objects.</li><li>Be careful when sharing object references across different parts of your application.</li><li>Choose the appropriate type based on the data’s purpose rather than memory assumptions.</li></ul><h3>Key Takeaways</h3><ul><li>Value types store the actual value.</li><li>Reference types store a reference to an object.</li><li>Assigning a value type creates a new copy of the data.</li><li>Assigning a reference type copies the reference, not the object.</li><li>Changes to a shared object are visible through every reference that points to it.</li><li>Understanding this distinction helps prevent many common bugs in C# applications.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2b4bcb79bb9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Modern ASP.NET Core Web APIs Use JWT Instead of Sessions]]></title>
            <link>https://ajax-workspace.medium.com/why-modern-asp-net-core-web-apis-use-jwt-instead-of-sessions-85aa22939838?source=rss-b9ec15fdfe93------2</link>
            <guid isPermaLink="false">https://medium.com/p/85aa22939838</guid>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[token]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[jwt-authentication]]></category>
            <dc:creator><![CDATA[Ajay Narkhedkar]]></dc:creator>
            <pubDate>Sun, 19 Jul 2026 07:10:00 GMT</pubDate>
            <atom:updated>2026-07-19T07:10:00.241Z</atom:updated>
            <content:encoded><![CDATA[<p>Modern applications are no longer limited to a single website. A business may have an Angular application, a mobile app, an admin dashboard, and third-party integrations — all using the same ASP.NET Core Web API.</p><p>Now imagine every request asking the server, <em>“Who is this user?”</em> and <em>“Can this user access this resource?”</em> If authentication is not designed properly, it can become difficult to manage as the application grows.</p><p>This is why many modern ASP.NET Core Web APIs use <strong>JWT (JSON Web Token)</strong> instead of traditional session-based authentication.</p><p>In this article, we’ll understand <strong>what JWT authentication is, why it became popular, how it differs from sessions, and how it works at a high level</strong>. We won’t generate tokens or write authentication code yet — that will come in the next articles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Q7CKiDNttE1OO-Ti_Y4xQ.png" /></figure><h4>What Is JWT Authentication?</h4><p>JWT (JSON Web Token) is a <strong>token-based authentication mechanism</strong> used by APIs to identify users after they log in.</p><p>Instead of asking users to enter their username and password on every request, the API verifies the user’s credentials once during login. If the credentials are valid, it creates a JWT and sends it back to the client.</p><p>The client stores this token and includes it with every protected API request.</p><pre>Login<br>   ↓<br>API Validates User<br>   ↓<br>JWT Generated<br>   ↓<br>Client Stores JWT<br>   ↓<br>Client Sends JWT with Every Request</pre><p>The API uses the token to identify the user before processing the request.</p><h3>Why Do Modern APIs Prefer JWT?</h3><p>To understand this, let’s first look at how traditional session authentication works.</p><p>Suppose you build an online shopping application called <strong>SecureShop</strong>.</p><p>When a customer logs in, the server creates a session and stores information such as:</p><ul><li>User ID</li><li>User Name</li><li>Login Status</li><li>User Role</li></ul><p>The browser receives only a <strong>Session ID</strong>.</p><p>Every future request sends that Session ID, and the server looks up the corresponding session before processing the request.</p><pre>Browser<br>   ↓<br>Session ID<br>   ↓<br>Server<br>   ↓<br>Session Storage<br>   ↓<br>User Information</pre><p>This works well for many traditional web applications.</p><p>However, modern applications often have multiple clients:</p><ul><li>Angular Web Application</li><li>Mobile Application</li><li>Admin Dashboard</li><li>Partner APIs</li></ul><p>All of them communicate with the same ASP.NET Core Web API.</p><p>Instead of maintaining server-side session information for every client, JWT allows the client to carry a signed token that represents the authenticated user.</p><p>This makes authentication more flexible for API-based applications.</p><h3>Sessions vs JWT</h3><p>Both approaches solve the same problem — identifying authenticated users — but they do it differently.</p><p>Session AuthenticationJWT AuthenticationServer stores login informationClient stores the JWTClient sends Session IDClient sends JWTServer looks up sessionServer validates the tokenCommon in MVC applicationsCommon in REST APIsRequires session managementUses token-based authentication</p><p>Neither approach is universally better.</p><p>If you’re building a traditional ASP.NET Core MVC application, sessions may still be an excellent choice.</p><p>If you’re building APIs consumed by different applications, JWT is often a better fit.</p><h3>How Does JWT Authentication Work?</h3><p>At a high level, the process is straightforward.</p><h3>Step 1: User Logs In</h3><p>The user submits login credentials.</p><pre>POST /api/auth/login</pre><pre>{<br>  &quot;email&quot;: &quot;customer@secureshop.com&quot;,<br>  &quot;password&quot;: &quot;Password@123&quot;<br>}</pre><h3>Step 2: API Validates Credentials</h3><p>The API checks whether the email and password are correct.</p><p>If they are invalid, the login request is rejected.</p><p>If they are valid, the API continues to the next step.</p><h3>Step 3: API Generates a JWT</h3><p>Instead of creating a server-side session, the API generates a JWT.</p><p>The token represents the authenticated user.</p><p>The client receives something similar to this:</p><pre>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...</pre><p>Don’t worry about what this token contains yet.</p><p>We’ll completely break it down in the next article.</p><h3>Step 4: Client Stores the Token</h3><p>The application stores the JWT after a successful login.</p><p>From this point onward, the user does not need to log in before every request.</p><h3>Step 5: Client Sends the JWT</h3><p>Whenever the client calls a protected API, it sends the token using the HTTP Authorization header.</p><pre>Authorization: Bearer eyJhbGciOiJIUzI1NiIs...</pre><p>The word <strong>Bearer</strong> simply means that the client is presenting this token as proof of authentication.</p><h3>Internal Authentication Flow</h3><p>The entire authentication process looks like this.</p><pre>User<br>   │<br>   │ Login<br>   ▼<br>ASP.NET Core Web API<br>   │<br>   │ Validate Credentials<br>   ▼<br>Generate JWT<br>   │<br>   │ Return Token<br>   ▼<br>Client<br>   │<br>   │ Bearer Token<br>   ▼<br>Protected API<br>   │<br>   │ Validate Token<br>   ▼<br>Process Request</pre><p>Notice something important.</p><p>The user’s password is sent <strong>only during login</strong>.</p><p>Every protected request afterward uses the JWT instead of the password.</p><p>This reduces unnecessary credential transmission and provides a standard way for APIs to identify users.</p><h3>Practical Example</h3><p>Let’s continue with our <strong>SecureShop API</strong>.</p><p>The application contains three protected endpoints.</p><pre>GET /api/products</pre><pre>GET /api/orders</pre><pre>GET /api/profile</pre><p>A customer first logs in.</p><pre>POST /api/auth/login</pre><p>After successful authentication, the API returns a JWT.</p><p>Now the customer requests their profile.</p><pre>GET /api/profile<br>Authorization: Bearer eyJhbGciOiJIUzI1NiIs...</pre><p>Before executing the request, the API validates the token.</p><p>If the token is valid, the request continues.</p><p>If the token is missing or invalid, the API rejects the request.</p><p>This simple flow allows the same API to work with:</p><ul><li>Angular applications</li><li>React applications</li><li>Mobile apps</li><li>Desktop applications</li><li>Third-party clients</li></ul><p>All clients authenticate in exactly the same way.</p><h3>Why Is JWT Popular for APIs?</h3><p>JWT became popular because it fits naturally into modern API architecture.</p><p>Some practical benefits include:</p><ul><li>It works well with different client applications.</li><li>It avoids server-side session dependency for every request.</li><li>It is suitable for distributed applications running on multiple servers.</li><li>It provides a standard authentication mechanism supported by ASP.NET Core.</li><li>It works well with cloud-native and microservice-based applications.</li></ul><p>These advantages make JWT a common choice for RESTful Web APIs.</p><h3>Common Mistakes</h3><p>When developers first start learning JWT, they often make a few common assumptions.</p><h3>Mistake 1: Thinking JWT Is Encrypted</h3><p>A JWT is usually <strong>encoded and digitally signed</strong>, not encrypted.</p><p>Its contents can often be viewed by anyone who has the token.</p><p>Because of this, never store sensitive information such as:</p><ul><li>Passwords</li><li>OTPs</li><li>Credit card numbers</li><li>Database credentials</li></ul><p>Only include the information required for authentication and authorization.</p><h3>Mistake 2: Assuming JWT Replaces Security</h3><p>JWT is only an authentication mechanism.</p><p>Applications still need:</p><ul><li>HTTPS</li><li>Secure password storage</li><li>Proper authorization</li><li>Token expiration</li><li>Secure token storage</li></ul><p>JWT is one part of application security, not the entire security solution.</p><h3>Mistake 3: Believing Sessions Are Obsolete</h3><p>Many beginners think sessions are “old” and JWT is always the better option.</p><p>That’s not true.</p><p>Session authentication is still widely used and works very well for traditional server-rendered applications.</p><p>Choose the authentication approach based on your application’s architecture — not on popularity.</p><h3>Key Takeaways</h3><ul><li>JWT is a token-based authentication mechanism commonly used by ASP.NET Core Web APIs.</li><li>Users authenticate only once using their credentials.</li><li>After successful login, the API generates a JWT.</li><li>The client sends the JWT with every protected request.</li><li>The API validates the token before processing the request.</li><li>JWT is especially useful when multiple applications consume the same API.</li><li>Sessions and JWT both solve authentication problems, but they use different approaches.</li><li>Choosing between them depends on the application’s requirements.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85aa22939838" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>