<?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"><channel><title><![CDATA[Last Night Codes]]></title><description><![CDATA[Last Night Codes shares my journey through learning different programming languages and documenting my projects. Explore practical tips, insights, and personal ]]></description><link>https://www.lncodes.com</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1723729224812/fef6f468-7de9-423c-bad0-62de7c43a28e.png</url><title>Last Night Codes</title><link>https://www.lncodes.com</link></image><generator>RSS for Node</generator><lastBuildDate>Wed, 15 Apr 2026 11:12:54 GMT</lastBuildDate><atom:link href="https://www.lncodes.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[C# Asynchronous]]></title><description><![CDATA[Introduction
Hello all, today I back with another C# topic, and today I will share what i learned about C# Asynchronous. I hope with this article you will know more about C# Asynchronous and use it on your project.
What Is It?
Microsoft introduced as...]]></description><link>https://www.lncodes.com/csharp-asynchronous</link><guid isPermaLink="true">https://www.lncodes.com/csharp-asynchronous</guid><category><![CDATA[C#]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[Developer Insights]]></category><dc:creator><![CDATA[Theodorus Doni]]></dc:creator><pubDate>Wed, 05 Feb 2025 07:02:49 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1723747601126/1843a59e-a433-4307-b77d-06e81ce721d8.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>Hello all, today I back with another <a target="_blank" href="https://www.lncodes.com/series/csharp">C#</a> topic, and today I will share what i learned about C# Asynchronous. I hope with this article you will know more about C# Asynchronous and use it on your project.</p>
<h2 id="heading-what-is-it">What Is It?</h2>
<p>Microsoft introduced asynchronous programming in .NET Framework 4.0 to improve the handling of long-running tasks, such as file I/O, network communication, or database operations, without blocking the main thread.</p>
<p>In traditional synchronous programming, operations are executed in a sequential order, meaning one operation must complete before the next one can begin. In contrast, asynchronous programming allows other tasks to run concurrently while waiting for a long-running operation to finish.</p>
<h2 id="heading-why-implement-it"><strong>Why Implement It?</strong></h2>
<p>There are several pros and cons to consider before implement asynchronous in our project. Here are some of them:</p>
<h3 id="heading-pros">Pros</h3>
<ul>
<li><p>Enhances application responsiveness during long-running operations.</p>
</li>
<li><p>Increases application scalability by allowing concurrent task handling.</p>
</li>
<li><p>Optimizes resource usage by freeing up threads while waiting for tasks.</p>
</li>
</ul>
<h3 id="heading-cons">Cons</h3>
<ul>
<li><p>May introduce deadlocks if not managed carefully.</p>
</li>
<li><p>Can lead to unexpected behavior due to context switching.</p>
</li>
<li><p>Can make debugging more challenging because of non-linear execution.</p>
</li>
</ul>
<h2 id="heading-how-it-works">How It Works?</h2>
<p>To understand how asynchronous work in the system, let's implement it first. In C#, a basic asynchronous operation requires three key components: <code>async</code>, <code>Task</code>, and <code>await</code>.</p>
<ol>
<li><p><strong>Async</strong></p>
<p> This modifier is applied to methods to indicate they contain asynchronous operations and allows the method to use the await keyword.</p>
</li>
<li><p><strong>Await</strong></p>
<p> This keyword is used before calling an asynchronous method. It tells the compiler to pause the execution of the current method until the awaited task completes. Importantly, it doesn’t block the thread and lets the program continue executing other tasks while waiting for the asynchronous operation to finish.</p>
</li>
<li><p><strong>Task Or Task&lt;T&gt;</strong></p>
<p> These keywords represent an asynchronous operation. <code>Task</code> is used when the operation doesn’t return a value, and <code>Task&lt;T&gt;</code> is used when the operation returns a value of type <code>T</code> asynchronously.</p>
</li>
</ol>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> System;
<span class="hljs-keyword">using</span> System.Threading.Tasks;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">Lncodes.Example.Async</span>;

<span class="hljs-keyword">public</span> <span class="hljs-keyword">sealed</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Program</span>
{
    <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">Main</span>(<span class="hljs-params"><span class="hljs-keyword">string</span>[] args</span>)</span>
    {
        <span class="hljs-keyword">await</span> LoadAssetAsync();
    }

    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">LoadAssetAsync</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-keyword">await</span> Task.Delay(<span class="hljs-number">2000</span>);
        Console.WriteLine(<span class="hljs-string">$"Asset loaded."</span>);
    }
}
</code></pre>
<p>In the code above, I have created an asynchronous method that will await 2 seconds before print "<em>Asset loaded.</em>" on the console. After implementing an asynchronous method in the code, here's what will happen in the system:</p>
<ol>
<li><p>When an asynchronous method is called, it doesn't automatically run on a separate thread. Instead, it begins executing synchronously until it reaches the first <code>await</code> keyword.</p>
</li>
<li><p>When the <code>await</code> keyword is encountered, the method is divided into two parts. The code before <code>await</code> runs immediately, while the code after <code>await</code> is delayed and executes later as a continuation (or callback) once the awaited operation completes (e.g., <code>await Task.Delay(2000)</code>).</p>
</li>
<li><p>When the operation of <code>await</code> is running, the system will handle the threading differently. If the operation is I/O-bound (e.g., database query, file reading, or web request), the operation is sent to the OS kernel to allow it to communicate with the hardware (e.g., network card or disk controller). However, if the operation is CPU-bound (e.g., heavy calculations), it will be sent to another thread in the thread pool.</p>
</li>
<li><p>Once the awaited operation completes, the Task Scheduler ensures the continuation executes in the correct context. If a <code>SynchronizationContext</code> is present (such as in a UI or ASP.NET application), it ensures the continuation is synchronized and runs in the appropriate context (e.g., back on the main thread) to prevent race conditions.</p>
</li>
</ol>
<h2 id="heading-console-application">Console Application</h2>
<p>In my console application, I use an asynchronous approach to create a game asset loader. This implementation ensures that assets like textures and audio files load without blocking the main thread. It also includes a cancellation feature, allowing the loading process to be stopped when necessary.</p>
<p>Below is a list of the classes I used to create this console application, along with a brief explanation of each class:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Class</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td>GameAssetLoader</td><td>This class is responsible for asynchronously loading game assets such as textures and audio files.</td></tr>
<tr>
<td>Program</td><td>This class is used to execute the game asset loading process asynchronously.</td></tr>
</tbody>
</table>
</div><div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://youtu.be/SlrpWXUBWQA">https://youtu.be/SlrpWXUBWQA</a></div>
<p> </p>
<p>In the video above, the console application displays the asynchronous loading process of game assets, including textures and audio files, and shows how the process can be canceled midway.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">ℹ</div>
<div data-node-type="callout-text">The source code for this console application can be viewed and downloaded at <a target="_blank" class="text-editor-link" href="https://github.com/lncodes/csharp-asynchronous">Project Repository – Github</a></div>
</div>

<h2 id="heading-additional-information">Additional Information</h2>
<p>I have discovered some additional information about C# Asynchronous. If you have any additional information regarding C# Asynchronous that you'd like to share, please feel free to leave a comment.</p>
<h3 id="heading-naming-guidelines">Naming Guidelines</h3>
<p>When implementing asynchronous, following specific naming guidelines can help ensure code readability and consistency. Here are some naming conventions recommended by Microsoft:</p>
<ul>
<li>Do use 'Async' suffix for asynchronous method e.g. <code>TimerAsync</code>, <code>PushDataAsync</code>, etc.</li>
</ul>
<h3 id="heading-further-discoveries">Further Discoveries</h3>
<p>Here are some further discoveries I have gathered from various sources that may provide a deeper understanding of C# Asynchronous:</p>
<ul>
<li><p>Avoid using <code>.Result</code> or <code>.Wait()</code> to get results from a <code>Task</code>, as they can cause deadlocks. A better approach is to use <code>await</code>, which allows asynchronous code to run without blocking the current thread. Deadlocks are particularly problematic in UI applications and other scenarios where maintaining thread responsiveness is essential.</p>
</li>
<li><p>The <code>ConfigureAwait(false)</code> method can be used to improve the performance of asynchronous operations by preventing the continuation from capturing the original synchronization context. However, be cautious, as it may cause issues if your code depends on running on a specific thread, such as when updating the UI in desktop applications.</p>
</li>
<li><p>Avoid using <code>async void</code>, as it can lead to race conditions by allowing the calling code to continue without waiting for the asynchronous method to finish. Use <code>async void</code> only in cases where awaiting the method’s completion is unnecessary. In all other situations, prefer returning a <code>Task</code> or <code>Task&lt;T&gt;</code> to handle asynchronous operations more effectively.</p>
</li>
<li><p>Before .NET 4.5, <code>Task.Factory.StartNew()</code> was commonly used to create and start tasks with flexible configurations. However, starting with .NET 4.5, <code>Task.Run()</code> became the preferred option for simpler task creation and execution, as it runs tasks on the <code>ThreadPool</code> by default without needing additional configuration, unlike <code>Task.Factory.StartNew()</code>.</p>
</li>
<li><p>A <code>CancellationToken</code> is used to signal and manage cancellation requests in asynchronous operations, allowing them to be interrupted or stopped before they complete.</p>
</li>
<li><p>A <code>ValueTask</code> can be used instead of a <code>Task</code> in asynchronous methods where the operation might complete synchronously or when the result can be produced without needing to await any operations.</p>
</li>
</ul>
<h2 id="heading-reference">Reference</h2>
<ol>
<li><p><a target="_blank" href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/">C# Asynchronous – Microsoft</a></p>
</li>
<li><p><a target="_blank" href="https://docs.microsoft.com/en-us/archive/msdn-magazine/2011/february/msdn-magazine-parallel-computing-it-s-all-about-the-synchronizationcontext">Synchronization Context – Microsoft</a></p>
</li>
<li><p><a target="_blank" href="https://www.youtube.com/watch?v=J0mcYVxJEl0">Deep Dive C# Asynchronous – NDC Conferences</a></p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Facade Design Pattern]]></title><description><![CDATA[Introduction
Hello all, today I back with another Design Patterns topic, and today I will share what i learned about Facade design pattern. I hope with this article you will know more about Facade design pattern and use it on your project.
What It Is...]]></description><link>https://www.lncodes.com/facade-design-pattern</link><guid isPermaLink="true">https://www.lncodes.com/facade-design-pattern</guid><category><![CDATA[design patterns]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[Developer Insights]]></category><dc:creator><![CDATA[Theodorus Doni]]></dc:creator><pubDate>Fri, 31 Jan 2025 02:04:41 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1738288741654/fc94aafc-5095-4b99-bed9-45b50bb41a64.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>Hello all, today I back with another <a target="_blank" href="https://www.lncodes.com/series/design-patterns">Design Patterns</a> topic, and today I will share what i learned about Facade design pattern. I hope with this article you will know more about Facade design pattern and use it on your project.</p>
<h2 id="heading-what-it-is">What It Is?</h2>
<p>The Facade design pattern is a structural pattern that simplifies access to a complex subsystem by providing a unified, high-level interface for the client. This pattern hides the internal details of the subsystems from the client, making it easier for the client to interact with the subsystems.</p>
<h2 id="heading-when-to-use-it">When To Use It?</h2>
<p>Here are some scenarios where implementing the Facade design pattern can be beneficial to a project:</p>
<ul>
<li><p>When the client needs a simple way to access complex subsystems.</p>
</li>
<li><p>When there’s a need to decouple the client from the subsystems.</p>
</li>
<li><p>When it’s important to reduce dependencies between the client and the subsystems.</p>
</li>
<li><p>When the client needs to access several related parts of subsystems through a single access point.</p>
</li>
</ul>
<h2 id="heading-why-implement-it">Why Implement It?</h2>
<p>Here are some pros and cons to consider before implementing the Facade design pattern in a project:</p>
<h3 id="heading-pros">Pros</h3>
<ul>
<li><p>Reduces the complexity of client code by unifying the interface that interacts with multiple subsystems.</p>
</li>
<li><p>Decouples the client code from the internal details of the subsystems, making it easier to change subsystem implementations without changing the client code.</p>
</li>
<li><p>Reduces the number of dependencies for the client, as it only interacts with a single facade instead of multiple subsystems.</p>
</li>
<li><p>Improves readability by hiding unnecessary details of the subsystem in the client’s code.</p>
</li>
<li><p>Enhances scalability by allowing new features to be added to the facade without modifying the existing subsystem classes.</p>
</li>
</ul>
<h3 id="heading-cons">Cons</h3>
<ul>
<li><p>Might become a "God Object" if it manages too many subsystems, making the system harder to maintain and violating the Single Responsibility Principle.</p>
</li>
<li><p>Might make debugging and extending the system challenging if it hides too much of the underlying complexity.</p>
</li>
<li><p>Might create a single point of failure that affects the entire system if it fails, as it often acts as the only access point to subsystems.</p>
</li>
<li><p>Might reduce flexibility for the client if it is designed to restrict direct access to subsystem components, which could limit the use of certain features or functionalities of the subsystems.</p>
</li>
</ul>
<h2 id="heading-how-to-implement-it">How To Implement It?</h2>
<p>Here are the steps to implement the Facade design pattern in a project:</p>
<ol>
<li><p>Identify the complex subsystem operations that the client needs to simplify.</p>
</li>
<li><p>Create a facade class that acts as a middle layer between the client and the subsystems.</p>
</li>
<li><p>In the facade class, create high-level methods that perform multiple subsystem operations.</p>
</li>
<li><p>In the client, use the facade class to replace all the subsystem operations.</p>
</li>
</ol>
<h3 id="heading-structure">Structure</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1737797131868/1f6d059b-136b-4d4b-bcd0-53d5612ce7c5.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-pseudocode">Pseudocode</h3>
<pre><code class="lang-apache"><span class="hljs-attribute">BEGIN</span> CLASS SubsystemA
    <span class="hljs-attribute">BEGIN</span> PUBLIC PROCEDURE operationA()
        <span class="hljs-attribute">PRINT</span> <span class="hljs-string">"Running SubsystemA Operation"</span>
    <span class="hljs-attribute">END</span> PROCEDURE
<span class="hljs-attribute">END</span> CLASS
</code></pre>
<pre><code class="lang-apache"><span class="hljs-attribute">BEGIN</span> CLASS SubsystemB
    <span class="hljs-attribute">BEGIN</span> PUBLIC PROCEDURE operationB()
        <span class="hljs-attribute">PRINT</span> <span class="hljs-string">"Running SubsystemB Operation"</span>
    <span class="hljs-attribute">END</span> PROCEDURE
<span class="hljs-attribute">END</span> CLASS
</code></pre>
<pre><code class="lang-apache"><span class="hljs-attribute">BEGIN</span> CLASS SubsystemC
    <span class="hljs-attribute">BEGIN</span> PUBLIC PROCEDURE operationC()
        <span class="hljs-attribute">PRINT</span> <span class="hljs-string">"Running SubsystemC Operation"</span>
    <span class="hljs-attribute">END</span> PROCEDURE
<span class="hljs-attribute">END</span> CLASS
</code></pre>
<pre><code class="lang-apache"><span class="hljs-attribute">BEGIN</span> CLASS Facade
    <span class="hljs-attribute">PRIVATE</span> FIELD subsystemA = new SubsystemA()
    <span class="hljs-attribute">PRIVATE</span> FIELD subsystemB = new SubsystemB()
    <span class="hljs-attribute">PRIVATE</span> FIELD subsystemC = new SubsystemC()

    <span class="hljs-attribute">BEGIN</span> PUBLIC PROCEDURE execute()
        <span class="hljs-attribute">subsystemA</span>.OperationA()
        <span class="hljs-attribute">subsystemB</span>.OperationB()
        <span class="hljs-attribute">subsystemC</span>.OperationC()
    <span class="hljs-attribute">END</span> PROCEDURE
<span class="hljs-attribute">END</span> CLASS
</code></pre>
<pre><code class="lang-apache"><span class="hljs-attribute">BEGIN</span> CLASS Client
    <span class="hljs-attribute">BEGIN</span> PRIVATE PROCEDURE useFacade()
        <span class="hljs-attribute">FIELD</span> facade = new Facade()
        <span class="hljs-attribute">facade</span>.Execute()
    <span class="hljs-attribute">END</span> PROCEDURE
<span class="hljs-attribute">END</span> CLASS
</code></pre>
<div data-node-type="callout">
<div data-node-type="callout-emoji">ℹ</div>
<div data-node-type="callout-text">The source code for the Facade design pattern in various programming languages can be viewed and downloaded on the <a target="_self" class="text-editor-link" href="https://github.com/lncodes/facade-design-pattern">Project Repository – Github</a>.</div>
</div>

<h2 id="heading-additional-information">Additional Information</h2>
<p>I have discovered some additional information about Facade design pattern. If you have any additional information about Facade design pattern that you'd like to share, please feel free to leave a comment.</p>
<h3 id="heading-facade-design-pattern-vs-adapter-design-pattern">Facade Design Pattern VS Adapter Design Pattern</h3>
<p>Both Facade and Adapter design patterns have similar code structures. Due to these similarities, choosing between them can be challenging. Here are some key factors to consider before making a decision:</p>
<ul>
<li><p>The Facade design pattern focuses on simplifying the interaction with complex subsystems by providing a unified interface, while the Adapter design pattern focuses on making two incompatible interfaces work together by providing a translation layer between them.</p>
</li>
<li><p>The Facade design pattern usually works with a set of classes or an entire subsystem, whereas the Adapter design pattern works with a single class or component.</p>
</li>
</ul>
<h3 id="heading-further-discoveries">Further Discoveries</h3>
<p>Here are some further discoveries I have gathered from various sources that may provide a deeper understanding of Facade design pattern:</p>
<ul>
<li><p>The Facade design pattern doesn't require the client to use every operation in the subsystem because it only wraps the essential operations.</p>
</li>
<li><p>The Facade design pattern is often used in libraries and frameworks to provide a simplified interface for the user.</p>
</li>
<li><p>The Facade design pattern can be combined with the Singleton design pattern, especially when the facade represents a global point of access for various subsystems.</p>
</li>
<li><p>The Facade design pattern can be used to manage security features by controlling access to specific subsystems.</p>
</li>
<li><p>The Facade design pattern can act as a boundary between different layers in a layered architecture. For example, it can act as a boundary between the presentation layer and the business logic layer to simplify their interaction.</p>
</li>
<li><p>The Facade design pattern doesn't change the behavior of the subsystems but simply provides a simplified interface to them.</p>
</li>
<li><p>The Facade design pattern makes unit testing easier by simplifying the subsystems' interface, allowing tests to focus on the simplified interface instead of multiple subsystems.</p>
</li>
</ul>
<h2 id="heading-reference">Reference</h2>
<ol>
<li><p><a target="_blank" href="https://sourcemaking.com/design_patterns/facade">Facade Design Pattern – Sourcemaking</a></p>
</li>
<li><p><a target="_blank" href="https://refactoring.guru/design-patterns/facade">Facade Design Pattern – Refactoring.guru</a></p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Adapter Design Pattern]]></title><description><![CDATA[Introduction
Hello all, today I back with another Design Patterns topic, and today I will share what i learned about Adapter design pattern. I hope with this article you will know more about Adapter design pattern and use it on your project.
What It ...]]></description><link>https://www.lncodes.com/adapter-design-pattern</link><guid isPermaLink="true">https://www.lncodes.com/adapter-design-pattern</guid><category><![CDATA[design patterns]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[Developer Insights]]></category><dc:creator><![CDATA[Theodorus Doni]]></dc:creator><pubDate>Tue, 21 Jan 2025 09:16:21 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1737450895727/36ddcc83-0655-4283-8bb1-9b188cf68936.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>Hello all, today I back with another <a target="_blank" href="https://www.lncodes.com/series/design-patterns">Design Patterns</a> topic, and today I will share what i learned about Adapter design pattern. I hope with this article you will know more about Adapter design pattern and use it on your project.</p>
<h2 id="heading-what-it-is">What It Is?</h2>
<p>The Adapter design pattern is a structural pattern that allows objects with incompatible interfaces to work together. It acts as a bridge between incompatible interfaces by making one interface compatible with another.</p>
<h2 id="heading-when-to-use-it">When To Use It?</h2>
<p>Here are some scenarios where implementing the Adapter design pattern can be beneficial to a project:</p>
<ul>
<li><p>When two or more classes or systems with incompatible interfaces need work together.</p>
</li>
<li><p>When there’s a need to integrate new components with legacy code that uses different or outdated interfaces.</p>
</li>
<li><p>When there’s a need to use a third-party library or external service that doesn't match the design of the current system.</p>
</li>
<li><p>When the existing code can’t be modified but still needs to work with the new system.</p>
</li>
</ul>
<h2 id="heading-why-implement-it">Why Implement It?</h2>
<p>Here are some pros and cons to consider before implementing the Adapter design pattern in a project:</p>
<h3 id="heading-pros">Pros</h3>
<ul>
<li><p>Increases compatibility by allowing systems with incompatible interfaces to work together without modifying their source code.</p>
</li>
<li><p>Adheres to the Single Responsibility Principle by isolating interface-related logic within the adapter classes.</p>
</li>
<li><p>Adheres to the Open-Closed Principle by enabling the creation of new adapters without modifying the existing system's code.</p>
</li>
<li><p>Increases scalability by allowing seamless integration of new components or systems without modifying existing code.</p>
</li>
</ul>
<h3 id="heading-cons">Cons</h3>
<ul>
<li><p>Increases complexity by adding an adapter layer to the system, which can make debugging and maintaining the code more difficult.</p>
</li>
<li><p>May require constant maintenance if the interface of the adapted class changes regularly.</p>
</li>
</ul>
<h2 id="heading-how-to-implement-it">How To Implement It?</h2>
<p>Here are the steps to implement the Adapter design pattern in a project:</p>
<ol>
<li><p>Identify the existing class (Adaptee) that has an incompatible interface with the current system.</p>
</li>
<li><p>Create an interface or abstract class that has a compatible interface with the current system.</p>
</li>
<li><p>Create an adapter class that implements the interface or abstract class.</p>
</li>
<li><p>Create a field in the adapter class to store a reference to the existing class (Adaptee) so the adapter can access the existing class's incompatible interface.</p>
</li>
<li><p>Implement the methods defined in the interface or abstract class in the adapter class. Within these methods, call the corresponding methods (The incompatible interface) of the existing class (Adaptee) to make it compatible with the current system.</p>
</li>
<li><p>Use the adapter class in the client to interact with the existing class (Adaptee) seamlessly.</p>
</li>
</ol>
<h3 id="heading-structure">Structure</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1737796306399/cdce6f52-3147-4f89-8d04-e3039d63a1e1.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-pseudocode">Pseudocode</h3>
<pre><code class="lang-apache"><span class="hljs-attribute">BEGIN</span> CLASS Adaptee
    <span class="hljs-attribute">BEGIN</span> PUBLIC FUNCTION getSpecificRequest()
        <span class="hljs-attribute">RETURN</span> <span class="hljs-string">"Specific request."</span>
    <span class="hljs-attribute">END</span> FUNCTION
<span class="hljs-attribute">END</span> CLASS
</code></pre>
<pre><code class="lang-apache"><span class="hljs-attribute">BEGIN</span> INTERFACE IAdapter
    <span class="hljs-attribute">FUNCTION</span> getRequest(): string
<span class="hljs-attribute">END</span> INTERFACE
</code></pre>
<pre><code class="lang-apache"><span class="hljs-attribute">BEGIN</span> CLASS Adapter IMPLEMENTS IAdapter
    <span class="hljs-attribute">PRIVATE</span> FIELD adaptee

    <span class="hljs-attribute">BEGIN</span> PUBLIC CONSTRUCTOR Adapter(adaptee)
        <span class="hljs-attribute">this</span>.adaptee = adaptee
    <span class="hljs-attribute">END</span> CONSTRUCTOR

    <span class="hljs-attribute">BEGIN</span> PUBLIC FUNCTION getRequest()
        <span class="hljs-attribute">return</span> adaptee.getSpecificRequest()
    <span class="hljs-attribute">END</span> FUNCTION
<span class="hljs-attribute">END</span> CLASS
</code></pre>
<pre><code class="lang-apache"><span class="hljs-attribute">BEGIN</span> CLASS Client
    <span class="hljs-attribute">BEGIN</span> PRIVATE PROCEDURE useAdapter()
        <span class="hljs-attribute">FIELD</span> adaptee = new Adaptee()
        <span class="hljs-attribute">FIELD</span> iAdapter = new Adapter(adaptee)
        <span class="hljs-attribute">FIELD</span> result = iAdapter.getRequest()
    <span class="hljs-attribute">END</span> PROCEDURE
<span class="hljs-attribute">END</span> CLASS
</code></pre>
<div data-node-type="callout">
<div data-node-type="callout-emoji">ℹ</div>
<div data-node-type="callout-text">The source code for the Adapter design pattern in various programming languages can be viewed and downloaded on the <a target="_self" class="text-editor-link" href="https://github.com/lncodes/adapter-design-pattern">Project Repository – Github</a>.</div>
</div>

<h2 id="heading-additional-information">Additional Information</h2>
<p>I have discovered some additional information about Adapter design pattern. If you have any additional information about Adapter design pattern that you'd like to share, please feel free to leave a comment.</p>
<h3 id="heading-adapter-design-pattern-vs-facade-design-pattern">Adapter Design Pattern VS Facade Design Pattern</h3>
<p>Both Adapter and Facade design patterns have similar code structures. Due to these similarities, choosing between them can be challenging. Here are some key factors to consider before making a decision:</p>
<ul>
<li><p>The Adapter design pattern focuses on making two incompatible interfaces work together by providing a translation layer between them, while the Facade design pattern focuses on simplifying the interaction with complex subsystems by providing a unified interface.</p>
</li>
<li><p>The Adapter design pattern usually works with a single class or component, whereas the Facade design pattern works with a set of classes or an entire subsystem.</p>
</li>
</ul>
<h3 id="heading-adapter-design-pattern-vs-decorator-design-pattern">Adapter Design Pattern VS Decorator Design Pattern</h3>
<p>Both Adapter and Decorator design patterns have similar code structures. Due to these similarities, choosing between them can be challenging. Here are some key factors to consider before making a decision:</p>
<ul>
<li><p>The Adapter design pattern focuses on making two incompatible interfaces work together by providing a translation layer between them, while the Decorator design pattern focuses on adding new functionality to objects.</p>
</li>
<li><p>The Adapter design pattern usually works with a single class or component (One adapter per one incompatible interface), whereas the Decorator design pattern often involves stacking multiple decorators to add several layers of functionality.</p>
</li>
</ul>
<h3 id="heading-further-discoveries">Further Discoveries</h3>
<p>Here are some further discoveries I have gathered from various sources that may provide a deeper understanding of Adapter design pattern:</p>
<ul>
<li><p>The Adapter design pattern can be implemented using either inheritance (extending the Adaptee class) or composition (using an object reference inside the adapter). Composition is generally preferred because it avoids tightly coupling between the adapter and the Adaptee class.</p>
</li>
<li><p>The Adapter design pattern doesn't have to implement all methods from the target interface, instead it only needs to "adapt" the necessary methods of the Adaptee class to ensure compatibility with the current system.</p>
</li>
<li><p>The Adapter design pattern can be combined with the Facade design pattern to provide a simpler interface for the client to interact with multiple adaptees.</p>
</li>
<li><p>The Adapter design pattern can be combined with the Decorator design pattern to add extra functionality to an adaptee without changing its core structure.</p>
</li>
</ul>
<h2 id="heading-reference">Reference</h2>
<ol>
<li><p><a target="_blank" href="https://sourcemaking.com/design_patterns/adapter">Adapter Design Pattern – Sourcemaking</a></p>
</li>
<li><p><a target="_blank" href="https://refactoring.guru/design-patterns/adapter">Adapter Design Pattern – Refactoring.guru</a></p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Builder Design Pattern]]></title><description><![CDATA[Introduction
Hello all, today I back with another Design Patterns topic, and today I will share what i learned about Builder design pattern. I hope with this article you will know more about Builder design pattern and use it on your project.
What It ...]]></description><link>https://www.lncodes.com/builder-design-pattern</link><guid isPermaLink="true">https://www.lncodes.com/builder-design-pattern</guid><category><![CDATA[design patterns]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[Developer Insights]]></category><dc:creator><![CDATA[Theodorus Doni]]></dc:creator><pubDate>Wed, 15 Jan 2025 03:17:05 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1736905789412/84b9164f-fea7-46ce-a118-7de003390eaf.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>Hello all, today I back with another <a target="_blank" href="https://www.lncodes.com/series/design-patterns">Design Patterns</a> topic, and today I will share what i learned about Builder design pattern. I hope with this article you will know more about Builder design pattern and use it on your project.</p>
<h2 id="heading-what-it-is">What It Is?</h2>
<p>The Builder design pattern is a creational pattern that provides a way to construct complex objects step by step. Builder design pattern allows us to reuse the same construction steps to build different types of the object, It decouples the object construction logic from the object representation.</p>
<h2 id="heading-when-to-use-it">When To Use It?</h2>
<p>Here are some scenarios where implementing the Builder design pattern can be beneficial to a project:</p>
<ul>
<li><p>When constructing an object requires multiple steps, configurations, or optional parameters, making direct construction complex and inefficient.</p>
</li>
<li><p>When improving code readability is necessary, as the pattern decouples object construction logic from its representation.</p>
</li>
<li><p>When there is a need to constructing immutable objects that require all attributes to be set during their initialization.</p>
</li>
<li><p>When there is a need to constructing different variations of an object using the same construction process.</p>
</li>
</ul>
<h2 id="heading-why-implement-it">Why Implement It?</h2>
<p>Here are some pros and cons to consider before implementing the Builder design pattern in a project:</p>
<h3 id="heading-pros">Pros</h3>
<ul>
<li><p>Makes complex object construction easier to understand.</p>
</li>
<li><p>Ensures consistent object construction across the application.</p>
</li>
<li><p>Decouples the construction logic from the business logic of the object.</p>
</li>
<li><p>Makes it easy to add new attributes or configurations without modifying existing code.</p>
</li>
</ul>
<h3 id="heading-cons">Cons</h3>
<ul>
<li><p>Increases code complexity by introducing additional classes and methods.</p>
</li>
<li><p>Might cause minor performance issues when used to create simple objects.</p>
</li>
<li><p>Can lead to tight coupling between the pattern and the objects it constructs.</p>
</li>
</ul>
<h2 id="heading-how-to-implement-it">How To Implement It?</h2>
<p>Here are the steps to implement the Builder design pattern in a project:</p>
<ol>
<li><p>Define the product class that needs to be constructed.</p>
</li>
<li><p>Define an interface or abstract class with methods to build the parts of the product.</p>
</li>
<li><p>Implement the builder interface or abstract class into concrete builder class with methods and construct the product steps by steps.</p>
</li>
<li><p>Create a director class isolates the construction process from the client.</p>
</li>
<li><p>In the client code, instantiate the director to construct the product and retrieve the final result.</p>
</li>
</ol>
<h3 id="heading-structure">Structure</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1737796337184/68415466-b9ca-42ed-a834-44dd848efe15.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-pseudocode">Pseudocode</h3>
<pre><code class="lang-apache"><span class="hljs-attribute">BEGIN</span> CLASS Product
    <span class="hljs-attribute">PUBLIC</span> FIELD partA
    <span class="hljs-attribute">PUBLIC</span> FIELD partB
    <span class="hljs-attribute">PUBLIC</span> FIELD partC

    <span class="hljs-attribute">BEGIN</span> PUBLIC CONSTRUCTOR Product(partA, partB, partC)
        <span class="hljs-attribute">this</span>.partA = partA
        <span class="hljs-attribute">this</span>.partB = partB
        <span class="hljs-attribute">this</span>.partC = partC
    <span class="hljs-attribute">END</span> CONSTRUCTOR
<span class="hljs-attribute">END</span> CLASS
</code></pre>
<pre><code class="lang-apache"><span class="hljs-attribute">BEGIN</span> INTERFACE IBuilder
    <span class="hljs-attribute">PUBLIC</span> PROCEDURE setPartA()
    <span class="hljs-attribute">PUBLIC</span> PROCEDURE setPartB()
    <span class="hljs-attribute">PUBLIC</span> PROCEDURE setPartC()
    <span class="hljs-attribute">PUBLIC</span> FUNCTION build(): Product
<span class="hljs-attribute">END</span> INTERFACE
</code></pre>
<pre><code class="lang-apache"><span class="hljs-attribute">BEGIN</span> CLASS ConcreteBuilder IMPLEMENTS IBuilder
    <span class="hljs-attribute">PRIVATE</span> FIELD partA
    <span class="hljs-attribute">PRIVATE</span> FIELD partB
    <span class="hljs-attribute">PRIVATE</span> FIELD partC

    <span class="hljs-attribute">BEGIN</span> PUBLIC PROCEDURE setPartA()
        <span class="hljs-attribute">partA</span> = <span class="hljs-string">"PartA"</span>
    <span class="hljs-attribute">END</span> PROCEDURE 

    <span class="hljs-attribute">BEGIN</span> PUBLIC PROCEDURE setPartB()
        <span class="hljs-attribute">partB</span> = <span class="hljs-string">"PartB"</span>
    <span class="hljs-attribute">END</span> PROCEDURE

    <span class="hljs-attribute">BEGIN</span> PUBLIC PROCEDURE setPartC()
        <span class="hljs-attribute">partC</span> = <span class="hljs-string">"PartC"</span>
    <span class="hljs-attribute">END</span> PROCEDURE

    <span class="hljs-attribute">BEGIN</span> PUBLIC FUNCTION build()
        <span class="hljs-attribute">RETRUN</span> new Product(partA, partB, partC)
    <span class="hljs-attribute">END</span> FUNCTION
<span class="hljs-attribute">END</span> CLASS
</code></pre>
<pre><code class="lang-apache"><span class="hljs-attribute">BEGIN</span> CLASS Director
    <span class="hljs-attribute">PRIVATE</span> FIELD builder: IBuilder

    <span class="hljs-attribute">BEGIN</span> PUBLIC CONSTRUCTOR Director(builder: IBuilder)
        <span class="hljs-attribute">this</span>.builder = builder
    <span class="hljs-attribute">END</span> CONSTRUCTOR

    <span class="hljs-attribute">BEGIN</span> PUBLIC PROCEDURE setBuilder(builder: IBuilder)
        <span class="hljs-attribute">this</span>.builder = builder
    <span class="hljs-attribute">END</span> PROCEDURE 

    <span class="hljs-attribute">BEGIN</span> PUBLIC FUNCTION construct()
        <span class="hljs-attribute">iBuilder</span>.setPartA()
        <span class="hljs-attribute">iBuilder</span>.setPartB()
        <span class="hljs-attribute">iBuilder</span>.setPartC()
        <span class="hljs-attribute">RETRUN</span> iBuilder.build();
    <span class="hljs-attribute">END</span> FUNCTION
<span class="hljs-attribute">END</span> CLASS
</code></pre>
<pre><code class="lang-apache"><span class="hljs-attribute">BEGIN</span> CLASS Client
    <span class="hljs-attribute">BEGIN</span> PRIVATE PROCEDURE useBuilder()
        <span class="hljs-attribute">FIELD</span> builder = new ConcreteBuilder()
        <span class="hljs-attribute">FIELD</span> director = new Director(builder)
        <span class="hljs-attribute">FIELD</span> result = director.construct()
    <span class="hljs-attribute">END</span> PROCEDURE
<span class="hljs-attribute">END</span> CLASS
</code></pre>
<div data-node-type="callout">
<div data-node-type="callout-emoji">ℹ</div>
<div data-node-type="callout-text">The source code for the Builder design pattern in various programming languages can be viewed and downloaded on the <a target="_self" class="text-editor-link" href="https://github.com/lncodes/builder-design-pattern">Project Repository – Github</a>.</div>
</div>

<h2 id="heading-additional-information">Additional Information</h2>
<p>I have discovered some additional information about Builder design pattern. If you have any additional information about Builder design pattern that you'd like to share, please feel free to leave a comment.</p>
<ul>
<li><p>The Builder design pattern can be combined with <a target="_blank" href="https://www.lncodes.com/singleton-design-pattern">Singleton Design Pattern</a> to make the builder accessible throughout the system.</p>
</li>
<li><p>The Builder design pattern can be combined with the Fluent Interface design pattern to simplify the construction steps, making the code easier to read and maintain, especially when constructing complex objects.</p>
</li>
<li><p>The Builder design pattern is often used to construct objects of classes that have many constructor parameters (usually more than three). However, it’s a good idea to first check if the class can be simplified, as having too many parameters might indicate that the class is too complex or violates the Single Responsibility Principle (SRP).</p>
</li>
</ul>
<h2 id="heading-reference">Reference</h2>
<ol>
<li><p><a target="_blank" href="https://sourcemaking.com/design_patterns/builder">Builder Design Pattern – Sourcemaking</a></p>
</li>
<li><p><a target="_blank" href="https://refactoring.guru/design-patterns/builder">Builder Design Pattern – Refactoring.guru</a></p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Singleton Design Pattern]]></title><description><![CDATA[Introduction
Hello all, today I back with another Design Patterns topic, and today I will share what i learned about Singleton design pattern. I hope with this article you will know more about Singleton design pattern and use it on your project.
What...]]></description><link>https://www.lncodes.com/singleton-design-pattern</link><guid isPermaLink="true">https://www.lncodes.com/singleton-design-pattern</guid><category><![CDATA[design patterns]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[Developer Insights]]></category><dc:creator><![CDATA[Theodorus Doni]]></dc:creator><pubDate>Fri, 04 Oct 2024 01:32:41 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1736905758673/ba362b77-34d5-4dea-bbae-900e319a4beb.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>Hello all, today I back with another <a target="_blank" href="https://www.lncodes.com/series/design-patterns">Design Patterns</a> topic, and today I will share what i learned about Singleton design pattern. I hope with this article you will know more about Singleton design pattern and use it on your project.</p>
<h2 id="heading-what-it-is">What It Is?</h2>
<p>The Singleton design pattern is a creational pattern that ensures a class has only one instance throughout the application's lifecycle. By providing global access to this instance, the pattern allows developers to easily retrieve and use the same instance whenever needed.</p>
<h2 id="heading-when-to-use-it">When To Use It?</h2>
<p>Here are some scenarios where implementing the Singleton design pattern can be beneficial to a project:</p>
<ul>
<li><p>When a single access point is essential for managing a shared resource or configuration, the Singleton design pattern ensures that only one instance is created and accessed throughout the application.</p>
</li>
<li><p>When multiple components need to access and share the same state or resource, such as a database connection or configuration setting, the Singleton design pattern provides a consistent and controlled way to manage that shared resource.</p>
</li>
<li><p>When managing limited resources, such as a thread pool or connection pool, the Singleton design pattern ensures efficient resource allocation while preventing resource exhaustion.</p>
</li>
</ul>
<h2 id="heading-why-implement-it"><strong>Why Implement It?</strong></h2>
<p>Here are some pros and cons to consider before implementing the Singleton design pattern in a project:</p>
<h3 id="heading-pros">Pros</h3>
<ul>
<li><p>Guarantees only one instance of a class exists, avoiding conflicts or duplication.</p>
</li>
<li><p>Provides a single point of access to the instance across the application.</p>
</li>
<li><p>Simplifies the handling of shared global state within the application.</p>
</li>
<li><p>Reduces resource consumption by avoiding multiple instances.</p>
</li>
</ul>
<h3 id="heading-cons">Cons</h3>
<ul>
<li><p>Violates the Single Responsibility Principle.</p>
</li>
<li><p>Can lead to race conditions in multi-threaded environments.</p>
</li>
<li><p>Can lead to hidden dependencies and make the code harder to maintain.</p>
</li>
<li><p>Can lead to tight coupling between components, making the code less flexible and harder to modify.</p>
</li>
</ul>
<h2 id="heading-how-to-implement-it">How To Implement It?</h2>
<p>Here are the steps to implement the Singleton design pattern in a project:</p>
<ol>
<li><p>Create a <code>private</code> constructor for the Singleton class to prevent other classes from creating instances of the Singleton class.</p>
</li>
<li><p>Create a <code>private static</code> variable that will hold the instance of the Singleton class to ensures that only one instance exists.</p>
</li>
<li><p>Create a <code>public static</code> method that returns the instance of the Singleton class. This method should check if the instance is <code>null</code> and create a new instance if it’s <code>null</code> to ensure controlled access to the single instance.</p>
</li>
</ol>
<h3 id="heading-structure">Structure</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1737796412885/333e6bb1-f038-48fc-8fc4-695e5f612886.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-pseudocode">Pseudocode</h3>
<pre><code class="lang-apache"><span class="hljs-attribute">BEGIN</span> CLASS Singleton
    <span class="hljs-attribute">PRIVATE</span> STATIC FIELD instance : Singleton

    <span class="hljs-attribute">BEGIN</span> PRIVATE CONSTRUCTOR Singleton
    <span class="hljs-attribute">END</span> CONSTRUCTOR

    <span class="hljs-attribute">BEGIN</span> PUBLIC STATIC FUNCTION getInstance()
        <span class="hljs-attribute">IF</span> instance is null then
            <span class="hljs-attribute">instance</span> = new Singleton()
        <span class="hljs-attribute">END</span> IF
        <span class="hljs-attribute">RETURN</span> instance
    <span class="hljs-attribute">END</span> FUNCTION
<span class="hljs-attribute">END</span> CLASS
</code></pre>
<pre><code class="lang-apache"><span class="hljs-attribute">BEGIN</span> CLASS Client
    <span class="hljs-attribute">BEGIN</span> PROCEDURE UseSingleton()
        <span class="hljs-attribute">FIELD</span> instance = Singleton.getInstance()
    <span class="hljs-attribute">END</span> PROCEDURE
<span class="hljs-attribute">END</span> CLASS
</code></pre>
<div data-node-type="callout">
<div data-node-type="callout-emoji">ℹ</div>
<div data-node-type="callout-text">The source code for the Singleton design pattern in various programming languages can be viewed and downloaded on the <a target="_blank" class="text-editor-link" href="https://github.com/lncodes/singleton-design-pattern">Project Repository – Github</a>.</div>
</div>

<h2 id="heading-additional-information">Additional Information</h2>
<p>I have discovered some additional information about Singleton design pattern. If you have any additional information about Singleton design pattern that you'd like to share, please feel free to leave a comment.</p>
<h3 id="heading-initialization-types">Initialization Types</h3>
<p>In the Singleton design pattern, the choice of initialization strategy plays a crucial role in determining when and how the instance is created. Here are the initialization types of the Singleton design pattern:</p>
<ol>
<li><p><strong>Eager Initialization</strong><br /> In this type of initialization, the Singleton instance is created as soon as the class is loaded into memory. This approach ensures that the instance is readily available whenever needed, which can be beneficial in applications where immediate access to the instance is required, or when the overhead of delayed instantiation is not acceptable.</p>
</li>
<li><p><strong>Lazy Initialization</strong><br /> In this type of initialization, the Singleton instance is created only when it is first accessed. This approach ensures that the instance is instantiated only when it truly needed, which can be beneficial to reduce resource usage.</p>
</li>
</ol>
<h3 id="heading-singleton-design-pattern-vs-static-class">Singleton Design Pattern VS Static Class</h3>
<p>Both Singleton design pattern and static classes provide similar functionality by ensuring that only a single instance can be created throughout the application's lifecycle. Due to these similarities, choosing between them can be challenging. Here are some key factors to consider before making a decision:</p>
<ul>
<li><p>A Singleton can only create one instance throughout the application lifecycle, whereas a static class cannot create any instances at all.</p>
</li>
<li><p>A Singleton can have both static and non-static members, while a static class can only contain static members.</p>
</li>
<li><p>A Singleton can maintain state through instance variables, while a static class can only maintain state through static fields.</p>
</li>
<li><p>A Singleton can from another class or implement interfaces, while a static class cannot inherit from any class or implement interfaces.</p>
</li>
</ul>
<h3 id="heading-further-discoveries">Further Discoveries</h3>
<p>Here are some further discoveries I have gathered from various sources that may provide a deeper understanding of Singleton design pattern:</p>
<ul>
<li><p>The Singleton design pattern can be combined with other design patterns, such as <strong>Abstract Factory</strong>, <strong>Builder</strong>, <strong>Facade</strong>, or <strong>Prototype</strong>.</p>
</li>
<li><p>When implementing the Singleton design pattern in a multithreaded environment, it’s important to consider thread safety. Techniques such as double-checked locking and using static constructors can help ensure that the Singleton instance remains thread-safe.</p>
</li>
<li><p>Some programming languages offer built-in classes or mechanisms for implementing lazy initialization. For example, in C#, the <code>Lazy&lt;T&gt;</code> class can be used to achieve lazy initialization.</p>
</li>
<li><p>Using dependency injection frameworks can provide a more flexible way to manage dependencies compared to traditional Singleton implementations.</p>
</li>
</ul>
<h2 id="heading-reference">Reference</h2>
<ol>
<li><p><a target="_blank" href="https://sourcemaking.com/design_patterns/singleton">Singleton Design Pattern – Sourcemaking</a></p>
</li>
<li><p><a target="_blank" href="https://refactoring.guru/design-patterns/singleton">Singleton Design Pattern – Refactoring.guru</a></p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[C# Generic]]></title><description><![CDATA[Introduction
Hello all, today I back with another C# topic, and today I will share what i learned about C# Generic. I hope with this article you will know more about C# Generic and use it on your project.
What It Is?
Introduced in C# 2.0, generic pro...]]></description><link>https://www.lncodes.com/csharp-generic</link><guid isPermaLink="true">https://www.lncodes.com/csharp-generic</guid><category><![CDATA[C#]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[Developer Insights]]></category><dc:creator><![CDATA[Theodorus Doni]]></dc:creator><pubDate>Sun, 01 Sep 2024 16:12:34 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1724413283292/dc900e10-322d-448b-9705-d2917888c284.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>Hello all, today I back with another <a target="_blank" href="https://www.lncodes.com/series/csharp">C#</a> topic, and today I will share what i learned about C# Generic. I hope with this article you will know more about C# Generic and use it on your project.</p>
<h2 id="heading-what-it-is">What It Is?</h2>
<p>Introduced in C# 2.0, generic provide a placeholder mechanism for defining types in classes, interfaces, or methods that can be replaced with specific types as needed, such as <code>int</code>, <code>float</code>, or <code>string</code>. These placeholders, known as type parameters, allow the same code to work with different data types while maintaining type safety.</p>
<h2 id="heading-why-implement-it">Why Implement It?</h2>
<p>There are several pros and cons to consider before implement a generic in our project. Here are some of them:</p>
<h3 id="heading-pros">Pros</h3>
<ul>
<li><p>Enhance code reusability.</p>
</li>
<li><p>Reducing runtime errors related to type mismatches.</p>
</li>
<li><p>Reduce the need to boxing and unboxing by enabling operations on value types directly.</p>
</li>
</ul>
<h3 id="heading-cons">Cons</h3>
<ul>
<li><p>Could potentially increase code size.</p>
</li>
<li><p>It may be challenging for new programmers to understand.</p>
</li>
<li><p>Could potentially impact performance because the Just-In-Time (JIT) compiler generates specific code for each generic type.</p>
</li>
</ul>
<h2 id="heading-how-it-works">How It Works?</h2>
<p>To understand how generic work in the system, let's implement it first. To implement a generic, all you need to do is add <code>&lt;T&gt;</code> after the method or class name, as shown in the code below:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">namespace</span> <span class="hljs-title">Lncodes.Example.Generic</span>;

<span class="hljs-keyword">public</span> <span class="hljs-keyword">sealed</span> <span class="hljs-keyword">class</span> <span class="hljs-title">QuizController</span>&lt;<span class="hljs-title">TQuestion</span>, <span class="hljs-title">TCorrectAnswer</span>&gt;
{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> TQuestion _question;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> TCorrectAnswer _correctAnswer;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">QuizController</span>(<span class="hljs-params">TQuestion question, TCorrectAnswer correctAnswer</span>)</span> =&gt;
       (_question, _correctAnswer) = (question, correctAnswer);
}
</code></pre>
<p>In the code above, I created a generic <code>QuizController</code> class with generic variables named <code>_question</code> and <code>_correctAnswer</code>. By using generic, I can customize the <code>_question</code> and <code>_correctAnswer</code> variable types as needed. After implementing generic, here's what happens in the system:</p>
<ol>
<li><p>When a generic type is defined using a specific reference type, the compiler sets up the generic class with a flexible type parameter. For example, if a <code>QuizController&lt;T&gt;</code> class is defined with the <code>int</code> type, the compiler prepares the class for this specific type in Microsoft Intermediate Language (MSIL).</p>
</li>
<li><p>When a specific generic class is prepared and the program is running, the Just-In-Time (JIT) compiler generates a specialized version of the generic type. For example, if <code>QuizController&lt;T&gt;</code> is instantiated with the <code>int</code> type, the JIT compiler creates a <code>QuizController&lt;int&gt;</code> class at runtime.</p>
</li>
<li><p>When a generic type is initialized with previously used type parameters, the system reuses the specialized version of the generic type that was already created by the JIT compiler. This reuse reduces the amount of generated code by minimizing the number of specialized classes created by the JIT compiler.</p>
</li>
<li><p>When assigning a type to a generic, the system by default allows any type to be assigned. However, adding a constraint limits which types can be used. To add a constraint, use the <code>where</code> keyword after the class name. For example, in <code>QuizController where TAnswer : List</code>, the <code>TAnswer</code> type must be a <code>List</code> or any class that inherits from <code>List</code>.</p>
</li>
</ol>
<h2 id="heading-console-application">Console Application</h2>
<p>In my console application, I use generic for my <code>QuizController</code> class, allowing me to customize the types of question, answer, and choices based on my needs.</p>
<p>Below is a list of the classes I used to create this console application, along with a brief explanation of each class:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Class</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td>QuizController</td><td>This class is used to manage quiz-related operations such as adding and deleting items.</td></tr>
<tr>
<td>Program</td><td>This class is used to display the quiz operation on the console.</td></tr>
</tbody>
</table>
</div><div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://youtu.be/FDb6rEfDuRU">https://youtu.be/FDb6rEfDuRU</a></div>
<p> </p>
<p>In the video above, the console application demonstrates three quiz variations, each using different data types for the answers and choices. All of these variations are managed by a single generic class called <code>QuizController</code>.</p>
<p>By using generic, handling different data types within a single class is greatly simplified. Instead of creating multiple versions of a class to accommodate different data types, a single generic class can be used to handle any type. This flexibility ensures that the code remains cleaner, more consistent, and easier to maintain over time, while also reducing the complexity of managing similar classes.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">ℹ</div>
<div data-node-type="callout-text">The source code for this console application can be viewed and downloaded at <a target="_blank" class="text-editor-link" href="https://github.com/lncodes/csharp-generic">Project Repository – Github.</a></div>
</div>

<h2 id="heading-additional-information">Additional Information</h2>
<p>I have discovered some additional information about C# Generic. If you have any additional information about C# Generic that you'd like to share, please feel free to leave a comment.</p>
<h3 id="heading-naming-guidelines">Naming Guidelines</h3>
<p>When implementing generics, following specific naming guidelines can help ensure code readability and consistency. Here are some naming conventions recommended by Microsoft:</p>
<ul>
<li><p>Do use a 'T' prefix with descriptive names for generic type parameters, e.g. <code>QuizController&lt;TQuestion&gt;</code>.</p>
</li>
<li><p>Consider using the single character 'T' for generic type parameters when there is only one type parameter, e.g. <code>QuizController&lt;T&gt;</code>.</p>
</li>
<li><p>Consider using names that indicate the constraints of generic type parameters when the generic has constraints, e.g. <code>QuizController&lt;TChoicesCollection&gt; where TChoicesCollection : ICollection</code>.</p>
</li>
</ul>
<h3 id="heading-further-discoveries">Further Discoveries</h3>
<p>Here are some further discoveries I have gathered from various sources that may provide a deeper understanding of C# Generic:</p>
<ul>
<li><p>Use generic instead of <code>object</code> or <code>dynamic</code> types whenever possible. <code>Object</code> requires boxing and unboxing processes, and <code>dynamic</code> requires runtime type resolution processes, both of which can lead to performance issues. Generic avoid these issues by removing the need for boxing, unboxing, and runtime type resolution, leading to better performance.</p>
  <div data-node-type="callout">
  <div data-node-type="callout-emoji">ℹ</div>
  <div data-node-type="callout-text">Boxing is the process of converting a value type, such as <code>int</code>, <code>float</code>, or <code>char</code>, into an <code>object</code> type. Unboxing is the process of converting an <code>object</code> type into a value type.</div>
  </div>

  <div data-node-type="callout">
  <div data-node-type="callout-emoji">ℹ</div>
  <div data-node-type="callout-text">Runtime type resolution is the process of checking the actual type of a variable, determining its specific type at runtime, and performing operations based on this type to ensure type safety.</div>
  </div>
</li>
<li><p>A generic method can be called without explicitly specifying the type parameter. For example, a generic method <code>CheckAnswer&lt;int&gt;(int answer)</code> can be invoked using <code>CheckAnswer(1)</code> instead of <code>CheckAnswer&lt;int&gt;(1)</code>. The compiler automatically infers the type parameter based on the provided argument.</p>
</li>
<li><p>A reflection can be used to get information about generic type at the runtime.</p>
  <div data-node-type="callout">
  <div data-node-type="callout-emoji">💡</div>
  <div data-node-type="callout-text">To learn more about C# Reflection, check out my post at <a target="_blank" class="text-editor-link" href="https://lncodes.com/csharp-reflection">C# Reflection - Last Night Codes</a>.</div>
  </div>


</li>
</ul>
<h2 id="heading-reference">Reference</h2>
<ol>
<li><p><a target="_blank" href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/">C# Generic – Microsoft</a></p>
</li>
<li><p><a target="_blank" href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters">C# Generic Constraints – Microsoft</a></p>
</li>
<li><p><a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/names-of-classes-structs-and-interfaces#names-of-generic-type-parameters">C# Generic Naming Guidelines - Microsoft</a></p>
</li>
<li><p><a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/identifier-names#naming-conventions">Pros And Cons U</a><a target="_blank" href="https://docs.microsoft.com/en-us/dotnet/standard/generics/">sing C# Generic – Microsoft</a></p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[C# Reflection]]></title><description><![CDATA[Introduction
Hello all, today I back with another C# topic, and today I will share what i learned about C# Reflection. I hope with this article you will know more about C# Reflection and use it on your project.
What It Is?
Reflection is a powerful fe...]]></description><link>https://www.lncodes.com/csharp-reflection</link><guid isPermaLink="true">https://www.lncodes.com/csharp-reflection</guid><category><![CDATA[C#]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[Developer Insights]]></category><dc:creator><![CDATA[Theodorus Doni]]></dc:creator><pubDate>Fri, 30 Aug 2024 15:37:10 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1723747624098/3ff25dec-6bb6-49b1-8752-f451593bd0e8.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>Hello all, today I back with another <a target="_blank" href="https://www.lncodes.com/series/csharp">C#</a> topic, and today I will share what i learned about C# Reflection. I hope with this article you will know more about C# Reflection and use it on your project.</p>
<h2 id="heading-what-it-is">What It Is?</h2>
<p>Reflection is a powerful feature that allows programs to inspect and interact with the metadata and structure of assemblies at runtime. It provides detailed information about a type, such as the names of constructors, fields, methods, and properties of a class. Additionally, reflection enables dynamic operations, such as creating class instances, modifying field values, instantiating generic types, and invoking methods.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">ℹ</div>
<div data-node-type="callout-text">Metadata is detailed information about code elements, such as assemblies, methods, fields, and other parts of the code.</div>
</div>

<h2 id="heading-why-implement-it">Why Implement It?</h2>
<p>There are several pros and cons to consider before implement reflection in our project. Here are some of them:</p>
<h3 id="heading-pros">Pros</h3>
<ul>
<li><p>It can be used to access private methods and members of a class, which is useful for unit testing and debugging.</p>
</li>
<li><p>It can be used to build flexible systems like plugins, where types can be loaded and used easily.</p>
</li>
</ul>
<h3 id="heading-cons">Cons</h3>
<ul>
<li><p>Could potentially increase code complexity.</p>
</li>
<li><p>It may be challenging for new programmers to understand.</p>
</li>
<li><p>It can pose security risks by revealing internal implementation details and sensitive data, as it can be used to access the private or protected members of a class.</p>
</li>
<li><p>It can impact performance, especially in performance-critical applications, due to the overhead of runtime type inspection and dynamic invocation.</p>
</li>
</ul>
<h2 id="heading-how-it-works">How It Works?</h2>
<p>To understand how reflection works in the system, let's see how to use it. To use reflection in the code, import the <code>System.Reflection</code> namespace. In this implementation, reflection is used to create an instance of a class with <code>Activator.CreateInstance&lt;&gt;</code>, retrieve field values with <code>.GetType()</code> and <code>.GetField()</code>, and invoke methods using <code>.Invoke()</code>, as shown in the code below:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> System.Reflection;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">Lncodes.Example.Reflection</span>;

<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Program</span>
{
    <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-keyword">var</span> abilityInstance = Activator.CreateInstance&lt;BaneAbilityController&gt;();
        FieldInfo[] fieldInfoCollection = abilityInstance.GetType().GetFields();
        MethodInfo[] methodInfoCollection = abilityInstance.GetType().GetMethods();

        <span class="hljs-keyword">foreach</span> (<span class="hljs-keyword">var</span> item <span class="hljs-keyword">in</span> fieldInfoCollection)
            Console.WriteLine(item.GetValue(abilityInstance));

        <span class="hljs-keyword">foreach</span> (<span class="hljs-keyword">var</span> item <span class="hljs-keyword">in</span> methodInfoCollection)
            item.Invoke(abilityInstance, <span class="hljs-literal">null</span>);
    }
}
</code></pre>
<p>In the code above, reflection is used to dynamically create an instance of the <code>BaneAbilityController</code> class, display all its field information, and invoke all its methods. Here's what will happen in the system once implementing reflection:</p>
<ol>
<li><p>Obtaining the <code>Type</code> object is a crucial step in accessing the metadata of a type when using reflection. This can be done using methods like <code>Assembly.GetType()</code> or <code>Type.GetType()</code>. Once the <code>Type</code> object is obtained, it provides detailed information about the type, enabling the system to dynamically inspect and manipulate its members.</p>
</li>
<li><p>After obtaining a <code>Type</code> object, reflection methods like <code>GetField()</code>, <code>GetMethod()</code>, or <code>GetProperties()</code> can be used to inspect its members. These methods create <code>FieldInfo</code>, <code>MethodInfo</code>, or <code>PropertyInfo</code> objects, which provide details about the type’s members, including their names, types, access modifiers, and custom attributes.</p>
</li>
<li><p>After obtaining <code>MethodInfo</code> objects, the <code>&lt;info&gt;.Invoke()</code> method can be used to invoke the method. before invoking the method, the system verifies that the method is safe to call by ensuring the arguments are correct and that the method has the required security permissions to be invoked.</p>
</li>
<li><p>After obtaining <code>FieldInfo</code> or <code>PropertyInfo</code> objects, the <code>&lt;info&gt;.GetValue()</code> method can be used to retrieve the value of the field or property. Before retrieving the value, the system checks if the field or property is static, ensures that the type of the object matches, and verifies that the access modifier allows access to retrieve the value.</p>
</li>
<li><p>The <code>Activator.CreateInstance()</code> method can be used to dynamically create instances of types. Before creating an instance, the system checks if the type can be instantiated, selects the appropriate constructor, and verifies that the constructor is suitable for creating the instance.</p>
</li>
</ol>
<div data-node-type="callout">
<div data-node-type="callout-emoji">ℹ</div>
<div data-node-type="callout-text">The <code>Type.InvokeMember()</code> method provides an alternative way to interact with type members by name, allowing operations like getting values, invoking methods, and creating instances. However, using <code>MethodInfo</code>, <code>FieldInfo</code>, or <code>PropertyInfo</code> offer a more precise and type-safe approach.</div>
</div>

<h2 id="heading-console-application"><strong>Console Application</strong></h2>
<p>In my console application, I use reflection to create instances, retrieve field information, invoke methods, and check if a field has a specific attribute in the ability hero classes. Each hero ability classes has unique field information and unique methods name and implementation.</p>
<p>Below is a list of the classes I used to create this console application, along with a brief explanation of each class:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Class</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td>AbilityController</td><td>This class is used as the parent class for all hero ability classes. It provides fundamental fields related to the ability's characteristics that can be adjusted by each derived class to meet the specific needs of its hero's abilities.</td></tr>
<tr>
<td>AbaddonAbilityController, BaneAbilityController, FlameLordAbilityController</td><td>These classes are used to implement unique ability methods and customize inherited characteristics to match each hero's unique abilities.</td></tr>
<tr>
<td>IgnoreAttribute</td><td>This class is used as an attribute to mark fields so that reflection ignores them, preventing those fields from being accessed or changed through reflection.</td></tr>
<tr>
<td>Program</td><td>This class is used to display information about hero ability classes. It shows the class name, field names along with their values, any fields with attributes, and method names along with their outputs.</td></tr>
</tbody>
</table>
</div><div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://youtu.be/m0vcJEkPPa4">https://youtu.be/m0vcJEkPPa4</a></div>
<p> </p>
<p>In the video above, the console application displays detailed information for each hero ability class. It shows the class name, field names with their values, and method names with their outputs. Additionally, fields marked with an 'Ignore' attribute will have their values hidden. All this information is gathered using reflection at runtime.</p>
<p>By using reflection, inspecting and interacting with type metadata at runtime becomes easier. Reflection provides access to the type information such as class names, field names, and method names, even when the types are not known at compile time. Reflection makes the code more adaptable to a variety of types encountered during runtime.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">ℹ</div>
<div data-node-type="callout-text">The source code for this console application can be viewed and downloaded at <a target="_blank" href="https://github.com/lncodes/csharp-reflection">Project Repository – Github</a>.</div>
</div>

<h2 id="heading-additional-information">Additional Information</h2>
<p>I have discovered some additional information about C# Reflection. If you have any additional information regarding C# Reflection that you'd like to share, please feel free to leave a comment.</p>
<h3 id="heading-reflection-performance-tips">Reflection Performance Tips</h3>
<p>Reflection can significantly affect performance by dynamically inspecting and interacting with a type and its members at runtime. To enhance efficiency and minimize these performance costs, consider the following practical tips:</p>
<ul>
<li><p>Use reflection only on the specific parts of a type or assembly that are needed. This helps reduce the amount of metadata the system needs to inspect and process.</p>
</li>
<li><p>Avoid using <code>BindingFlags.IgnoreCase</code> as it can potentially cause performance overhead. When this flag is used, the system needs to perform additional process by converting the member names of a type to a common letter case before comparing them.</p>
</li>
<li><p>Use <code>BindingFlags.ExactBinding</code> whenever the argument type matches the method parameter type. When this flag is used, the system will throw an error immediately if the argument types don't match, which improves performance by bypassing the type coercion process.</p>
  <div data-node-type="callout">
  <div data-node-type="callout-emoji">ℹ</div>
  <div data-node-type="callout-text">Type coercion is a process that changes one data type into another. This can occur either implicitly, where the conversion happens automatically, or explicitly, where the programmer specifies the conversion.</div>
  </div>
</li>
<li><p>Avoid using <code>Type.InvokeMember</code> because it is often less efficient and harder to maintain compared to specialized reflection methods. For better performance, clarity, and type safety, it's recommended to use dedicated methods like <code>MethodInfo.Invoke</code>, <code>PropertyInfo.GetValue</code>, or <code>FieldInfo.GetValue</code>.</p>
</li>
</ul>
<h3 id="heading-further-discoveries">Further Discoveries</h3>
<p>Here are some further discoveries I have gathered from various sources that may provide a deeper understanding of C# Reflection:</p>
<ul>
<li><p>The <code>BindingFlags</code> enumeration is used to determines which information want to retrieved from reflection. For example, using <code>typeof(&lt;class&gt;).GetMethods(BindingFlags.Public)</code> will return only the methods with a <code>public</code> access modifier from the specified class.</p>
</li>
<li><p>Reflection can make typed programming languages, such as C# or Java, behave more like dynamic languages by allowing code inspection and manipulation at runtime.</p>
</li>
<li><p>Use reflection wisely, as it breaks principles of typed programming languages, such as encapsulation and abstraction. It can bypass access restrictions and make the code more difficult to maintain.</p>
</li>
<li><p>Since C# 6, the <code>nameof</code> keyword offers a more efficient way to obtain names for fields, methods, properties, and other code elements compared to reflection. For example, <code>nameof(abilityInstance.Cooldown)</code> is better than <code>abilityInstance.Cooldown.GetType().Name</code> for retrieving the field name.</p>
</li>
<li><p>Since C# 6, the <code>nameof</code> keyword provides a more efficient alternative for obtaining field names compared to reflection. For example, use <code>nameof(abilityInstance.Cooldown)</code> rather than <code>abilityInstance.Cooldown.GetType().Name</code> to get the field name.</p>
</li>
<li><p>Use expression trees instead of reflection for tasks that involve dynamic code creation and execution. Expression trees provide better performance and type safety by allowing code to be compiled and optimized at runtime, unlike reflection, which depends on inspecting metadata at runtime.</p>
</li>
<li><p>Accessing metadata can increase the working set, leading to higher memory usage and more frequent memory allocations. This can result in more frequent garbage collection events to to handle the extra memory usage.</p>
  <div data-node-type="callout">
  <div data-node-type="callout-emoji">ℹ</div>
  <div data-node-type="callout-text">Working set refers to the amount of memory a program is currently using. A larger working set means the program is using more memory.</div>
  </div>


</li>
</ul>
<h2 id="heading-reference">Reference</h2>
<ol>
<li><p><a target="_blank" href="https://docs.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/reflection">C# Reflection – Microsoft</a></p>
</li>
<li><p><a target="_blank" href="https://docs.microsoft.com/en-us/dotnet/api/system.reflection.bindingflags">Binding Flags – Microsoft</a></p>
</li>
<li><p><a target="_blank" href="https://docs.microsoft.com/en-us/archive/msdn-magazine/2005/july/using-net-avoid-common-performance-pitfalls-for-speedier-apps">Deep Dive C# Reflection – Microsoft</a></p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[C# Delegate]]></title><description><![CDATA[Introduction
Hello all, today I back with another C# topic, and today I will share what i learned about C# Delegate. I hope with this article you will know more about C# Delegate and use it on your project.
What Is It?
A delegate is a type that holds...]]></description><link>https://www.lncodes.com/csharp-delegate</link><guid isPermaLink="true">https://www.lncodes.com/csharp-delegate</guid><category><![CDATA[C#]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[Developer Insights]]></category><dc:creator><![CDATA[Theodorus Doni]]></dc:creator><pubDate>Thu, 29 Aug 2024 16:36:15 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1723737601882/983dbc49-207c-4eb6-a6c0-68b84bcbbbe8.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>Hello all, today I back with another <a target="_blank" href="https://www.lncodes.com/series/csharp">C#</a> topic, and today I will share what i learned about C# Delegate. I hope with this article you will know more about C# Delegate and use it on your project.</p>
<h2 id="heading-what-is-it">What Is It?</h2>
<p>A delegate is a type that holds a reference to one or more methods. As a 'method holder', it enables methods to be stored and called dynamically, making it ideal for callbacks and event-driven programming.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">ℹ</div>
<div data-node-type="callout-text">A callback is a method that is called after a certain operation completes to perform a specific task.</div>
</div>

<h2 id="heading-why-implement-it">Why Implement It?</h2>
<p>There are several pros and cons to consider before implement an delegate in our project. Here are some of them:</p>
<h3 id="heading-pros">Pros</h3>
<ul>
<li><p>Enhance code reusability.</p>
</li>
<li><p>Enhance the clarity of the code flow.</p>
</li>
<li><p>Minimize dependencies on other classes.</p>
</li>
</ul>
<h3 id="heading-cons">Cons</h3>
<ul>
<li><p>It may be challenging for new programmers to understand.</p>
</li>
<li><p>Having too many methods assigned to a delegate could potentially cause performance overhead.</p>
</li>
</ul>
<h2 id="heading-how-it-works">How It Works?</h2>
<p>To understand how delegate work in the system, let's implement it first. To implement a delegate, all you need to do is use <code>delegate</code> keyword. However, starting .NET Framework 3.5, you can also use an <code>Action</code>, <code>Func</code> or <code>Predicate</code> keywords which are found in the <code>System</code> namespace, as shown in the code below:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> System;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">Lncodes.Example.Delegate</span>;

<span class="hljs-keyword">public</span> <span class="hljs-keyword">sealed</span> <span class="hljs-keyword">class</span> <span class="hljs-title">InventoryController</span>
{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> <span class="hljs-keyword">bool</span> _isReachMaxInventoryCapacity = <span class="hljs-literal">false</span>;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">AddItem</span>(<span class="hljs-params">Action successAddCallback, Action failAddCallback</span>)</span>
    {
        Console.WriteLine(<span class="hljs-string">"Adding Item"</span>);
        <span class="hljs-keyword">if</span> (_isReachMaxInventoryCapacity) failAddCallback();
        <span class="hljs-keyword">else</span> successAddCallback();
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Program</span>
{
    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-keyword">var</span> inventoryController = <span class="hljs-keyword">new</span> InventoryController();
        inventoryController.AddItem(SuccessAddCallback, FailAddCallback);
    }

    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">SuccessAddCallback</span>(<span class="hljs-params"></span>)</span> =&gt;
        Console.WriteLine(<span class="hljs-string">"Successfully added item to the inventory."</span>);

    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">FailAddCallback</span>(<span class="hljs-params"></span>)</span> =&gt;
        Console.WriteLine(<span class="hljs-string">"Failed to add item to inventory as it has reached its maximum capacity."</span>);
}
</code></pre>
<p>In the code above, I have created delegates as parameters of the <code>AddingItem()</code> method. These delegates are used as callbacks that get invoked every time an item is successfully added to the inventory or if it fails to be added. After implementing these delegates in the code, here's what will happen in the system:</p>
<ol>
<li><p>When a method is assigned to a delegate, the delegate holds a reference to that method.</p>
</li>
<li><p>When assigning a method to a delegate, the method’s parameters and return type must exactly match the delegate’s, or it will cause a compiler error.</p>
</li>
<li><p>When a delegate is called, it calls all the methods assigned to it sequentially.</p>
</li>
</ol>
<h2 id="heading-console-application">Console Application</h2>
<p>In my console application, delegates are used to manage callbacks for inventory actions. Whenever an item is added or removed from the inventory, a delegate is called to handle the action.</p>
<p>Below is a list of the classes I used to create this console application, along with a brief explanation of each class:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Class</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td><code>InventoryController</code></td><td>This class is used to manage inventory-related operations such as adding and deleting items.</td></tr>
<tr>
<td><code>Program</code></td><td>This class is used to display the delegate callbacks from inventory operations on the console.</td></tr>
</tbody>
</table>
</div><div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://youtu.be/-gJ0hcysHaU">https://youtu.be/-gJ0hcysHaU</a></div>
<p> </p>
<p>In the video above, the console application displays four different statuses after adding or deleting items in the inventory. Each status represents the use of a different type of delegate. Below is a list of all the delegate types used in this console application, along with a brief explanation of each delegate:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Delegate Types</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td><code>Action</code></td><td>This delegate is used to display the success status after adding the potion item to the inventory. The output can be seen in console message number 1.</td></tr>
<tr>
<td><code>Func</code></td><td>This delegate is used to get a random item to be added to the inventory. The output can be seen in console message number 2.</td></tr>
<tr>
<td><code>Predicate</code></td><td>This delegate is used to check if the inventory has reached its maximum capacity. The output can be seen in console message number 3.</td></tr>
<tr>
<td><code>Delegate</code></td><td>This delegate is used to display the success status after deleting an item from the inventory. The output can be seen in console message number 4.</td></tr>
</tbody>
</table>
</div><p>By using delegates, managing and handling inventory action callbacks becomes more efficient. Different delegate types for various inventory action callbacks enhance code clarity and ensure type safety. They also make the code more flexible and easier to maintain.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">ℹ</div>
<div data-node-type="callout-text">The source code for this console application can be viewed and downloaded at <a target="_blank" class="text-editor-link" href="https://github.com/lncodes/csharp-delegate">Project Repository – Github</a>.</div>
</div>

<h2 id="heading-additional-information">Additional Information</h2>
<p>I have discovered some additional information about C# Delegate. If you have any additional information regarding C# Delegate that you'd like to share, please feel free to leave a comment.</p>
<h3 id="heading-naming-guidelines">Naming Guidelines</h3>
<p>When implementing delegates, following specific naming guidelines can help ensure code readability and consistency. Here are some naming conventions recommended by Microsoft:</p>
<ul>
<li><p>Do use 'Callback' suffix for delegates that returns <code>void</code> type e.g. <code>Action successAddCallback</code>.</p>
</li>
<li><p>Do use 'Get' prefix for delegates that don't returns a <code>bool</code> type e.g. <code>Func&lt;int&gt; getRandomItemId</code>.</p>
</li>
<li><p>Do use 'Is', 'Can', or 'Has' prefix for delegates that return <code>bool</code> type e.g. <code>Predicate&lt;int&gt; canAddingItems</code>.</p>
</li>
<li><p>Don’t use 'Delegate' suffix for delegate names e.g. <code>delegate void DeleteItemDelegate()</code>.</p>
</li>
</ul>
<h3 id="heading-action-vs-func-vs-predicate">Action VS Func VS Predicate</h3>
<p><code>Action</code>, <code>Func</code>, and <code>Predicate</code> are all delegate types that offer similar functionalities for managing method references. Due to these similarities, choosing between them can be challenging. Here are some key factors to consider before making a decision:</p>
<ul>
<li><p>An <code>Action</code> delegate is a delegate that returns no value (void), typically used for callbacks or situations where an action needs to be executed without producing a result. It's equivalent to <code>delegate void OnComplete()</code>.</p>
</li>
<li><p>A <code>Func&lt;TReturn&gt;</code> delegate is a delegate that returns a value with specified type, typically used for operations that produce a result. It's equivalent to <code>delegate TReturn OnComplete()</code>.</p>
</li>
<li><p>A <code>Predicate&lt;TInput&gt;</code> delegate is a delegate that returns a <code>bool</code> type, typically used for validating input or determining whether an item meets certain criteria. It's equivalent to <code>delegate bool OnComplete(TInput input)</code>.</p>
</li>
</ul>
<h3 id="heading-further-discoveries">Further Discoveries</h3>
<p>Here are some further discoveries I have gathered from various sources that may provide a deeper understanding of C# Delegate:</p>
<ul>
<li><p>A delegate can be called using the <code>Invoke</code> method or directly as if it were a regular method.</p>
</li>
<li><p>A delegate that holds more than one method is known as a 'Multicast Delegate'.</p>
</li>
<li><p>Use the <code>?.</code> operator to check a nullable delegate e.g. <code>addingItemCallback?.Invoke();</code>. This practice prevents runtime errors by ensuring the delegate is only called when it’s not <code>null</code>.</p>
</li>
<li><p>Use the <code>delegate</code> keyword instead of <code>Action</code>, <code>Func</code>, or <code>Predicate</code> when creating a delegate with three or more parameters. This is because <code>Action</code>, <code>Func</code>, and <code>Predicate</code> don't allow naming their parameters, which can make the code harder to read. For example: <code>Action&lt;int, int, int&gt;</code> vs. <code>delegate void(int health, int damage, int speed)</code>.</p>
</li>
<li><p>Convert a 'Multicast Delegate' into an event if the methods assigned to it are defined outside the class declaration. Declaring it as an event ensures that the delegate can't be called from outside the class declaration, which enhances encapsulation and control over its usage.</p>
  <div data-node-type="callout">
  <div data-node-type="callout-emoji">💡</div>
  <div data-node-type="callout-text">To learn more about C# Event, check out my post at <a target="_blank" class="text-editor-link" href="https://lncodes.com/csharp-event">C# Event - Last Night Codes</a>.</div>
  </div>


</li>
</ul>
<h2 id="heading-reference">Reference</h2>
<ol>
<li><p><a target="_blank" href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/delegates/">C# Delegate – Microsoft</a></p>
</li>
<li><p><a target="_blank" href="https://docs.microsoft.com/en-us/dotnet/api/system.action">C# Action – Microsoft</a></p>
</li>
<li><p><a target="_blank" href="https://docs.microsoft.com/en-us/dotnet/api/system.func-1">C# Func – Microsoft</a></p>
</li>
<li><p><a target="_blank" href="https://docs.microsoft.com/en-us/dotnet/api/system.func-1">C# Predicate – Microsoft</a></p>
</li>
<li><p><a target="_blank" href="https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/names-of-classes-structs-and-interfaces#names-of-common-types">C# Delegate Naming Guidelines – Microsoft</a></p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[C# Interface]]></title><description><![CDATA[Introduction
Hello all, today I back with another C# topic, and today I will share what i learned about C# Interface. I hope with this article you will know more about C# Interface and use it on your project.
What It Is?
An interface can be thought o...]]></description><link>https://www.lncodes.com/csharp-interface</link><guid isPermaLink="true">https://www.lncodes.com/csharp-interface</guid><category><![CDATA[C#]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[Developer Insights]]></category><dc:creator><![CDATA[Theodorus Doni]]></dc:creator><pubDate>Thu, 29 Aug 2024 15:08:46 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1723747693944/48f12fea-b1b8-4f2f-b5e8-1f83530b8a5b.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>Hello all, today I back with another <a target="_blank" href="https://www.lncodes.com/series/csharp">C#</a> topic, and today I will share what i learned about C# Interface. I hope with this article you will know more about C# Interface and use it on your project.</p>
<h2 id="heading-what-it-is">What It Is?</h2>
<p>An interface can be thought of as a contract. This term is used because a class or struct that implements an interface is obligated to provide implementations for all of its members. For instance, if an interface have a method called <code>Attack()</code>, any class or struct that implements this interface must provide its own implementation of the <code>Attack()</code> method.</p>
<h2 id="heading-why-implement-it">Why Implement It?</h2>
<p>There are several pros and cons to consider before implement an interface in our project. Here are some of them:</p>
<h3 id="heading-pros">Pros</h3>
<ul>
<li><p>Enhance code scalability.</p>
</li>
<li><p>Enhance code reusability.</p>
</li>
<li><p>Loose coupling between modules.</p>
</li>
</ul>
<h3 id="heading-cons">Cons</h3>
<ul>
<li><p>Could potentially increase the amount of redundant code.</p>
</li>
<li><p>It may be challenging for new programmers to understand.</p>
</li>
<li><p>When adding a new contract, it's essential to implement it across all classes that inherit from it. This ensures that as more classes connect, the complexity of the system increases appropriately.</p>
</li>
</ul>
<h2 id="heading-how-it-works">How It Works?</h2>
<p>To understand how interface work in the system, let's implement it first. To implement an interface, all you need to do is create a class file. However, instead of using the <code>class</code> keyword, you should use the <code>interface</code> keyword, as shown in the code below:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> System;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">Lncodes.Example.Interface</span>;

<span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">IDamageable</span>
{
    <span class="hljs-keyword">int</span> Health { <span class="hljs-keyword">get</span>; }
    <span class="hljs-keyword">event</span> Action OnHealthRunsOut;
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">TakeDamage</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> amountDamage</span>)</span>;
}
</code></pre>
<p>In the code above, I have created an interface with a <code>Health</code> property, an <code>OnHealthRunsOut</code> event, and a <code>TakeDamage()</code> method. This interface is designed for any class that needs to handle damage-related interactions, such as, Enemy, Player, NPC. After implementing this interface in the code, here's what will happen in the system:</p>
<ol>
<li><p>When a class or struct implements an interface, the system will generate an error if that class or struct does not implement all the interface members.</p>
</li>
<li><p>When creating an interface as a variable type, the system will allow assigning objects of all classes or structs derived from this interface to the declared type, such as <code>IDamageable _damageable = new Enemy()</code> or <code>new Player()</code> or <code>new Npc()</code>.</p>
</li>
</ol>
<h2 id="heading-console-application">Console Application</h2>
<p>In my console application, interfaces are used to specify creature capabilities. One interface specifies which creatures can take damage, while another specifies which creatures can attack others. In this console application, both the player and the enemy can take damage and attack other creatures, whereas the NPC can only take damage.</p>
<p>Below is a list of the interfaces and classes I used to create this console application, along with a brief explanation of each interface and class:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Interface And Class</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td><code>IAttacker</code></td><td>This interface is used to define a contract for creatures that capable of attacking other creatures. It provides the necessary methods and properties for handling attack-related operations.</td></tr>
<tr>
<td><code>IDamageable</code></td><td>This interface is used to define a contract for creatures that capable of taking damage. It provides the necessary methods and properties for handling damage-related operations.</td></tr>
<tr>
<td><code>EnemyController</code>, <code>PlayerController</code></td><td>These classes are used to implement the <code>IAttacker</code> and <code>IDamagebale</code> interface contract.</td></tr>
<tr>
<td><code>NpcController</code></td><td>This class is used to implement <code>IDamageable</code> interface contract.</td></tr>
<tr>
<td><code>Program</code></td><td>This class is used to displaying the attack process of the attackable creature attacking the damageable creature until the damageable creature is defeated on the console.</td></tr>
</tbody>
</table>
</div><div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://youtu.be/7qqywzRsHOA">https://youtu.be/7qqywzRsHOA</a></div>
<p> </p>
<p>In the video above, you'll notice that each creatures has its own unique default health points. Additionally, when the enemy or player attack there's difference implementation on how they attack, the enemy sometimes miss the attack but the player never miss the attack and the damage points they have are also different from each other.</p>
<p>By implementing interfaces, the behaviors and attributes of creatures are clearly defined and managed. Interfaces provide specific rules for what each creature can do and what properties it should have. This leads to more organized and maintainable code by establishing a consistent structure, which makes it easier to update or add new features.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">ℹ</div>
<div data-node-type="callout-text">The source code for this console application can be viewed and downloaded at <a target="_blank" class="text-editor-link" href="https://github.com/lncodes/csharp-interface">Project Repository – Github.</a></div>
</div>

<h2 id="heading-additional-information">Additional Information</h2>
<p>I have discovered some additional information about C# Interface. If you have any additional information about C# Interface that you'd like to share, please feel free to leave a comment.</p>
<h3 id="heading-naming-guidelines">Naming Guidelines</h3>
<p>When implementing interfaces, following specific naming guidelines can help ensure code readability and consistency. Here are some naming conventions recommended by Microsoft:</p>
<ul>
<li><p>Use adjective phrases, or occasionally nouns or noun phrases, when naming interfaces e.g. <code>IDamageable</code>, <code>IPlayer</code>.</p>
  <div data-node-type="callout">
  <div data-node-type="callout-emoji">⚠</div>
  <div data-node-type="callout-text">Nouns and noun phrases should be used rarely for interface names. Frequent use might indicate that the interface could be more appropriately represented as an abstract class or a regular class.</div>
  </div>
</li>
<li><p>Do use 'I' prefix when naming interfaces e.g. <code>IAttacker</code>, <code>IDamageable</code>.</p>
</li>
</ul>
<h3 id="heading-interface-vs-abstract">Interface VS Abstract</h3>
<p>Both interfaces and abstract classes offer similar functionality for enhancing code abstraction by defining contracts or blueprints for derived classes. Due to these similarities, choosing between them can be challenging. Here are some key factors to consider before making a decision:</p>
<ul>
<li><p>Use an interface when its member functionality is designed to be used by multiple modules. For example, when creating an <code>IDamageable</code> interface, the functionality of its members is intended to be used across various modules, including player, NPC, and enemy modules. This inclusivity makes it ideal to use an interface rather than an abstract class.</p>
</li>
<li><p>Interface can't have methods with default implementations, but abstract class can have methods with default implementations.</p>
  <div data-node-type="callout">
  <div data-node-type="callout-emoji">ℹ</div>
  <div data-node-type="callout-text">Since C# 8, interface can have methods with default implementations. However, the object of the derived class can't call this method unless the derived class overrides it first.</div>
  </div>
</li>
<li><p>The only access modifier that can be used for the interface members is <code>public</code>. The <code>private</code>, <code>protected</code>, and <code>internal</code> access modifiers can't be used for the interface members. However, all access modifiers can be used in the abstract class members.</p>
  <div data-node-type="callout">
  <div data-node-type="callout-emoji">ℹ</div>
  <div data-node-type="callout-text">Since C# 8, interface members can use the <code>private</code>, <code>protected</code>, or <code>internal</code> access modifier.</div>
  </div>
</li>
<li><p>Interfaces can't have variables as a member, but abstract classes can have them as a member.</p>
</li>
<li><p>A class can inherit from multiple interfaces, but it can't inherit from multiple abstract classes.</p>
</li>
<li><p>A struct can inherit from an interface, but it can't inherit from an abstract class.</p>
</li>
</ul>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">To learn more about C# Abstract, check out my post at <a target="_blank" class="text-editor-link" href="https://lncodes.com/csharp-abstract">C# Abstract - Last Night Codes</a>.</div>
</div>

<h3 id="heading-further-discoveries">Further Discoveries</h3>
<p>Here are some further discoveries I have gathered from various sources that may provide a deeper understanding of C# Interface:</p>
<ul>
<li><p>The interface can't be instantiated.</p>
</li>
<li><p>Struct can inherit from an interface.</p>
</li>
<li><p>Interface can only have method, property, or event as a member.</p>
</li>
<li><p>If a class or struct implements an interface but does not fully utilize all of its contract, that interface needs to be divided into several smaller interfaces. This is necessary to avoid violating the Interface Segregation Principle (ISP), which is a key tenet of the SOLID principles.</p>
</li>
<li><p>An interface can be explicitly declared in its derived class, for example: <code>public int IDamageable.Health {get;}</code>.</p>
</li>
<li><p>Never create an interface if the interface doesn't have any members.</p>
</li>
</ul>
<h2 id="heading-reference">Reference</h2>
<ol>
<li><p><a target="_blank" href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/interface">C# Interface – Microsoft</a></p>
</li>
<li><p><a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/names-of-classes-structs-and-interfaces">C# Interface Naming Guidelines - Microsoft</a></p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[C# Event]]></title><description><![CDATA[Introduction
Hello all, today I back with another C# topic, and today I will share what i learned about C# Event. I hope with this article you will know more about C# Event and use it on your project.

⚠
Before diving deeper into C# Event, it’s recom...]]></description><link>https://www.lncodes.com/csharp-event</link><guid isPermaLink="true">https://www.lncodes.com/csharp-event</guid><category><![CDATA[C#]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[Developer Insights]]></category><dc:creator><![CDATA[Theodorus Doni]]></dc:creator><pubDate>Thu, 29 Aug 2024 02:40:15 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1723738133921/00293856-d9b0-44fa-8f30-6e35a3b1ef58.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>Hello all, today I back with another <a target="_blank" href="https://www.lncodes.com/series/csharp">C#</a> topic, and today I will share what i learned about C# Event. I hope with this article you will know more about C# Event and use it on your project.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">⚠</div>
<div data-node-type="callout-text">Before diving deeper into C# Event, it’s recommended to first read my C# Delegate post at <a target="_blank" href="https://lncodes.com/csharp-delegate">C# Delegate - Last Night Codes</a>.</div>
</div>

<h2 id="heading-what-it-is">What It Is?</h2>
<p>In C#, an event is a specialized form of delegate. Unlike delegates, which allow methods from outside the class to be assigned using both <code>=</code> and <code>+=</code> operators, an event restricts assignments to only using the <code>+=</code> operator. Additionally, events can only be raised within the class where they are declared, ensuring that they are raised only in controlled circumstances.</p>
<h2 id="heading-why-implement-it">Why Implement It?</h2>
<p>There are several pros and cons to consider before implement an event in our project. Here are some of them:</p>
<h3 id="heading-pros">Pros</h3>
<ul>
<li><p>Enhance the clarity of the code flow.</p>
</li>
<li><p>Minimize dependencies on other classes.</p>
</li>
<li><p>Preventing direct invocation of a delegate from outside its declaring class reduces the risk of unintended side effects.</p>
</li>
</ul>
<h3 id="heading-cons">Cons</h3>
<ul>
<li><p>It may be challenging for new programmers to understand.</p>
</li>
<li><p>Could potentially cause performance overhead if there's too many method assign to it.</p>
</li>
<li><p>Could potentially cause memory leaks If the event are not properly unsubscribed.</p>
</li>
</ul>
<h2 id="heading-how-it-works">How It Works?</h2>
<p>To understand how event work in the system, let's implement it first. To implement an event, all you need to do is add an <code>event</code> keyword in front of the <code>delegate</code>, there are two different types of delegate that can be used for an event:</p>
<ol>
<li><p>Regular Delegates e.g. <code>public event [delegate/Action/Func/Predicate] OnOpenButtonPressed;</code></p>
</li>
<li><p>Event Handler Delegates e.g. <code>public event EventHandler CloseButtonPressEventHandler;</code></p>
</li>
</ol>
<div data-node-type="callout">
<div data-node-type="callout-emoji">ℹ</div>
<div data-node-type="callout-text">To learn more about the differences between regular delegates and event handler delegates, see the section on Regular Delegates vs. Event Handler Delegates below.</div>
</div>

<p>The implementation of these events is as shown in the code below:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> System;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">Lncodes.Example.Event</span>;

<span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">class</span> <span class="hljs-title">UIController</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">event</span> Action OnOpenButtonPressed;
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">event</span> EventHandler CloseButtonPressEventHandler;
}
</code></pre>
<p>In the code above, I have created events using the <code>Action</code> delegate and the <code>EventHandler</code> delegate. These events are designed to be triggered whenever the open or close button is pressed. After implementing these events in the code, here's what will happen in the system:</p>
<ol>
<li><p>When a delegate is declared as an event, the system ensures that the event can only be raised within the class that declares it. Additionally, methods can only be assigned to the event using the <code>+=</code> operator.</p>
</li>
<li><p>Assigning and raising an event is similar to working with a delegate. When you assign a method to an event, it references that method. Raising the event will then also invoke all methods that have been added to it.</p>
</li>
</ol>
<h2 id="heading-console-application">Console Application</h2>
<p>In my console application, an event is used to display a message when a button is pressed. This console application uses three different types of delegates: <code>Action</code> (a general delegate without arguments), <code>EventHandler</code> (a specialized delegate without specific arguments), and <code>EventHandler&lt;T&gt;</code> (a specialized delegate with specific arguments).</p>
<p>Below is a list of the classes I used to create this console application, along with a brief explanation of each class:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Class</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td><code>UIController</code></td><td>This class is used as a parent class that manages general UI-related operations for all menu classes.</td></tr>
<tr>
<td><code>MainMenuUIController</code></td><td>This class is used to manage UI-related operations for the main menu.</td></tr>
<tr>
<td><code>ResultMenuUIController</code></td><td>This class is used to manage UI-related operations for the results menu.</td></tr>
<tr>
<td><code>CloseButtonEventArgs</code></td><td>This class is used to store event data that is passed through an <code>EventHandler</code>.</td></tr>
<tr>
<td><code>Program</code></td><td>This class is used to display button pressed events messages on the console.</td></tr>
</tbody>
</table>
</div><div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://youtu.be/8m9U541UXoA">https://youtu.be/8m9U541UXoA</a></div>
<p> </p>
<p>In the video above, the console application displays a message when the button is pressed. There are three different buttons, each representing a different type of delegate used to handle events. Below is a list of all the delegate types used in this console application, along with a brief explanation of each delegate:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Delegate Types</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td><code>event Action</code></td><td>This delegate is used to handle the event that is raised when the open button is pressed. The output can be seen in the console message no 1.</td></tr>
<tr>
<td><code>event EventHandler</code></td><td>This delegate is used to handle the event that is raised when the animate button is pressed. The output can be seen in the console message no 2.</td></tr>
<tr>
<td><code>event EventHandler&lt;String&gt;</code></td><td>This delegate is used to handle the event that is raised when the close button is pressed. The output can be seen in the console message no 3.</td></tr>
</tbody>
</table>
</div><p>By implementing events, managing and handling button actions becomes significantly more efficient. Additionally, using different delegate types for various events can further enhance action management. Each delegate type is designed to ensure that events are handled appropriately, leading to a more organized and effective event-handling process.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">ℹ</div>
<div data-node-type="callout-text">The source code for this console application can be viewed and downloaded at <a target="_blank" class="text-editor-link" href="https://github.com/lncodes/csharp-event">Project Repository – Github</a>.</div>
</div>

<h2 id="heading-additional-information">Additional Information</h2>
<p>I have discovered some additional information about C# Event. If you have any additional information about C# Event that you'd like to share, please feel free to leave a comment.</p>
<h3 id="heading-naming-guidelines">Naming Guidelines</h3>
<p>When implementing events, following specific naming guidelines can help ensure code readability and consistency. Here are some naming conventions recommended by Microsoft:</p>
<ul>
<li><p>Do use a verb or verb phrase when naming an event e.g., opening, closed, etc.</p>
</li>
<li><p>Do use verb-ing for event names that are raised before an operation is performed e.g., opening, closing, etc.</p>
</li>
<li><p>Do use verb-ed for event names that are raised after an operation is performed e.g., opened, closed, etc.</p>
</li>
<li><p>Do use 'On' prefix for the regular delegate event names, e.g. <code>public event Action OnOpenButtonPressed;</code>.</p>
</li>
<li><p>Do use 'EventHandler' suffix for event handler delegate event names e.g. <code>public event EventHandler CloseButtonPressEventHandler;</code>.</p>
</li>
<li><p>Do use the 'EventArgs' suffix for class or struct names that are intended to be used as arguments for <code>EventHandler</code> e.g. <code>public class CloseButtonEventArgs { }</code>.</p>
</li>
<li><p>Do use the 'On' prefix for method names that raise an <code>EventHandler</code> e.g. <code>protected void OnOpenButtonPressed()</code>.</p>
</li>
</ul>
<h3 id="heading-regular-delegate-vs-event-handler-delegate">Regular Delegate VS Event Handler Delegate</h3>
<p>Both regular delegates and event handler delegates have similar functionality to managing method references within an event-driven architecture. Due to these similarities, choosing between them can be challenging. Here are some key factors to consider before making a decision:</p>
<ul>
<li><p>When using <code>EventHandler</code>, there are two default parameters: <code>sender</code> and <code>eventArgs</code>. In contrast, regular delegates do not include these default parameters.</p>
</li>
<li><p>Use <code>EventHandler</code> when it’s important to know which object raised the event. For instance, in an inheritance architecture, <code>EventHandler</code> helps determine which child class is raising the event, thanks to its default <code>sender</code> parameter which provides the instance of the object that raised the event.</p>
</li>
</ul>
<div data-node-type="callout">
<div data-node-type="callout-emoji">ℹ</div>
<div data-node-type="callout-text">In my opinion, any delegate with two arguments (the sender and the event data) can be considered as an event handler delegate type, even if it's declared using a regular delegate e.g. <code>public event Func&lt;int, object, EventArgs&gt; OpenButtonEventHandler</code>.</div>
</div>

<h3 id="heading-event-vs-delegate">Event VS Delegate</h3>
<p>Both events and delegates have similar functionality to manage method references and provide a way to register methods. Due to these similarities, choosing between them can be challenging. Here are some key factors to consider before making a decision:</p>
<ul>
<li><p>An event is typically used to notify the subscribing classes when something occurs in the publisher class, while a delegate is typically used for callbacks or to pass methods as parameters.</p>
</li>
<li><p>An event can only be raised within the class where it’s declared, while a delegate can be invoked from outside its declaring class. This restriction helps ensure that the event’s handling remains encapsulated within the class that declares it.</p>
</li>
<li><p>Outside its class declaration, an event can only be modified by adding or removing event handlers using the <code>+=</code> and <code>-=</code> operators. In comparison, a delegate can be can be assigned or modified using <code>=</code>, <code>+</code>, <code>-</code>, <code>+=</code>, and <code>-=</code> operators.</p>
</li>
</ul>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">To learn more about C# Delegate, check out my post at <a target="_blank" class="text-editor-link" href="https://lncodes.com/csharp-delegate">C# Delegate - Last Night Codes</a>.</div>
</div>

<h3 id="heading-further-discoveries">Further Discoveries</h3>
<p>Here are some further discoveries I have gathered from various sources that may provide a deeper understanding of C# Event:</p>
<ul>
<li><p>When using <code>EventHandler</code> and no additional arguments are needed, it's recommended to use <code>EventArgs.Empty</code> instead of <code>null</code>. This maintains consistency and prevents null reference errors at runtime.</p>
</li>
<li><p>When using a static <code>EventHandler</code>, it's acceptable to pass <code>null</code> for the <code>sender</code> argument. However, for non-static <code>EventHandler</code> instances, avoid passing <code>null</code> as the <code>sender</code> argument.</p>
</li>
<li><p>When using the <code>EventHandler</code> delegate for an event, it’s essential to define a method to raise the event, and this method should be marked as <code>protected virtual</code>. This allows subclasses to override the method and raise the event, which is essential for properly implementing event handling in an inheritance-based architecture.</p>
</li>
<li><p>When an <code>EventHandler</code> that returns values is required, a custom <code>EventHandler</code> can be defined using a regular delegate, like <code>public event Func&lt;int, object, EventArgs&gt; CloseButtonPressEventHandler</code>.</p>
</li>
<li><p>Since C# 2.0, the generic <code>EventHandler&lt;T&gt;</code> can be used to define the type of argument for an <code>EventHandler</code>. This approach is recommended when the <code>EventHandler</code> needs to pass an argument, as it eliminates the need to cast the <code>EventArgs</code> parameter to access the argument value.</p>
</li>
</ul>
<h2 id="heading-reference">Reference</h2>
<ol>
<li><p><a target="_blank" href="https://docs.microsoft.com/en-us/dotnet/standard/events/">C# Event – Microsoft</a></p>
</li>
<li><p><a target="_blank" href="https://docs.microsoft.com/en-us/dotnet/api/system.eventhandler">C# Event Handler – Microsoft</a></p>
</li>
<li><p><a target="_blank" href="https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/event">C# Event Design Guidelines – Microsoft</a></p>
</li>
<li><p><a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/names-of-type-members#names-of-events">C# Event Naming Guidelines – Microsoft</a></p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[C# Abstract]]></title><description><![CDATA[Introduction
Hello all, today I back with another C# topic, and today I will share what i learned about C# Abstract. I hope with this article you will know more about C# Abstract and use it on your project.
What It Is?
An abstract class acts as a blu...]]></description><link>https://www.lncodes.com/csharp-abstract</link><guid isPermaLink="true">https://www.lncodes.com/csharp-abstract</guid><category><![CDATA[C#]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[Developer Insights]]></category><dc:creator><![CDATA[Theodorus Doni]]></dc:creator><pubDate>Wed, 28 Aug 2024 17:01:36 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1723747671210/751a397b-5d1b-4de5-8bc5-0161efaddff6.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>Hello all, today I back with another <a target="_blank" href="https://www.lncodes.com/series/csharp">C#</a> topic, and today I will share what i learned about C# Abstract. I hope with this article you will know more about C# Abstract and use it on your project.</p>
<h2 id="heading-what-it-is">What It Is?</h2>
<p>An abstract class acts as a blueprint for derived classes that inherit from it. By defining a class as <code>abstract</code>, you essentially create a class that is purely a design, without an actual implementation. This means that it's impossible to create an object of an <code>abstract</code> class, as the term "blueprint" suggests only represents the design and not the concrete implementation.</p>
<p>By defining a class as <code>abstract</code>, you can now create different derived classes that retain the same characteristics of the abstract class but with distinct implementations.</p>
<h2 id="heading-why-implement-it">Why Implement It?</h2>
<p>There are several pros and cons to consider before implement an abstract in our project. Here are some of them:</p>
<h3 id="heading-pros">Pros</h3>
<ul>
<li><p>Enhance code reusability.</p>
</li>
<li><p>Enhance code scalability.</p>
</li>
</ul>
<h3 id="heading-cons">Cons</h3>
<ul>
<li><p>Could potentially increase code complexity.</p>
</li>
<li><p>Subclass tightly coupled to the abstract class.</p>
</li>
<li><p>It may be challenging for new programmers to understand.</p>
</li>
</ul>
<h2 id="heading-how-it-works">How It Works?</h2>
<p>To understand how abstract work in the system, let's implement it first. To implement an abstract, all you need to do is add an <code>abstract</code> modifier to your class, method, or property, as shown in the code below:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">namespace</span> <span class="hljs-title">Lncodes.Example.Abstract</span>;

<span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">class</span> <span class="hljs-title">EnemyController</span>
{
    <span class="hljs-keyword">protected</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">int</span> Stamina { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Run</span>(<span class="hljs-params"></span>)</span>;
}
</code></pre>
<p>In the code above, I have created an abstract class for enemy. Within this class, I create an abstract property called <code>Stamina</code> and an abstract method named <code>Run()</code>. After implementing this abstract in the code, here's what will happen in the system:</p>
<ol>
<li><p>When creating an abstract class, the system will allow the creation of either an abstract method or an abstract property within the abstract class.</p>
</li>
<li><p>When creating an abstract class, the system will prohibit the creation of an instance of that class.</p>
</li>
<li><p>When creating an abstract method or abstract property, the system will automatically attach a <code>virtual</code> keyword to it in the background. As a result, an <code>override</code> keyword is necessary to modify the method or property in the derived class.</p>
</li>
<li><p>When creating a method or property with an <code>abstract</code> modifier in the parent class, all derived classes are required to provide an actual implementation to that method or property. This is because methods or properties with <code>abstract</code> modifiers have no actual implementation.</p>
</li>
</ol>
<h2 id="heading-console-application">Console Application</h2>
<p>In my console application, an abstract class is used to create a blueprint for all types of enemies. Each enemy type will have different stamina points and unique implementations for how they perform run and rest operations.</p>
<p>Below is a list of the classes I used to create this console application, along with a brief explanation of each class:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Class</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td><code>EnemyController</code></td><td>This class is used as a blueprint for each type of enemy.</td></tr>
<tr>
<td><code>TrollEnemyController</code>, <code>OrcEnemyController</code>, <code>GoblinEnemyController</code></td><td>These classes are used to implement the blueprint members of the <code>EnemyController</code> abstract class.</td></tr>
<tr>
<td><code>Program</code></td><td>This class is used to display information about a random enemy and show all the actions that the enemy performs in the console application.</td></tr>
</tbody>
</table>
</div><div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://youtu.be/AxMvAdpbIiA">https://youtu.be/AxMvAdpbIiA</a></div>
<p> </p>
<p>In the video above, you'll notice that each enemy type has its own unique default stamina points. Additionally, the stamina points used while running and gained while resting are different for each enemy type.</p>
<p>By implementing an abstract class, creating a new types of enemies has become significantly easier, thanks to the established blueprint of the <code>EnemyController</code> class.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">ℹ</div>
<div data-node-type="callout-text">The source code for this console application can be viewed and downloaded at <a target="_blank" class="text-editor-link" href="https://github.com/lncodes/csharp-abstract">Project Repository – Github</a>.</div>
</div>

<h2 id="heading-additional-information">Additional Information</h2>
<p>I have discovered some additional information about C# Abstract. If you have any additional information regarding C# Abstract that you'd like to share, please feel free to leave a comment.</p>
<h3 id="heading-abstract-vs-interface">Abstract VS Interface</h3>
<p>Both abstract classes and interfaces offer similar functionality for enhancing code abstraction by defining contracts or blueprints for derived classes. Due to these similarities, choosing between them can be challenging. Here are some key factors to consider before making a decision:</p>
<ul>
<li><p>Use an abstract class when the members functionality are exclusively used within a single module. For instance, when creating the <code>EnemyController</code> abstract class, we limited its functionality to be exclusively used within the enemies module, not for players or NPC. This exclusivity makes it ideal to use an abstract class rather than an interface.</p>
</li>
<li><p>Abstract class can have methods with default implementations, but interface can't have methods with default implementations.</p>
  <div data-node-type="callout">
  <div data-node-type="callout-emoji">ℹ</div>
  <div data-node-type="callout-text">Since C# 8, interface can have methods with default implementations. However, the object of the derived class can't call this method unless the derived class overrides it first.</div>
  </div>
</li>
<li><p>All access modifiers can be used in the abstract class members, but only the <code>public</code> access modifier can be used in an interface members.</p>
  <div data-node-type="callout">
  <div data-node-type="callout-emoji">ℹ</div>
  <div data-node-type="callout-text">Since C# 8, interface members can use the <code>private</code>, <code>protected</code>, or <code>internal</code> access modifier.</div>
  </div>
</li>
<li><p>Abstract class can have variables as a member, but interface can't have them as a member.</p>
</li>
<li><p>A class can't inherit from multiple abstract classes, but it can inherit from multiple interfaces.</p>
</li>
<li><p>A struct can't inherit from an abstract class, but it can inherit from an interface.</p>
</li>
</ul>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">To learn more about C# Interface, check out my post at <a target="_blank" class="text-editor-link" href="https://lncodes.com/csharp-interface">C# Interface - Last Night Codes</a>.</div>
</div>

<h3 id="heading-abstract-method-vs-virtual-method">Abstract Method VS Virtual Method</h3>
<p>Both abstract methods and virtual methods offer similar functionality in providing flexible method implementations for derived classes. Due to these similarities, choosing between them can be challenging. Here are some key factors to consider before making a decision:</p>
<ul>
<li><p>Use the abstract method when the majority of the methods in the derived class have different implementations. However, if only a minority of the derived classes requires a different implementation, use virtual instead of abstract.</p>
</li>
<li><p>When using abstract method, it's mandatory to override the method in the derived class. Conversely, there is no requirement to override a virtual method in the derived class. This is because abstract method don't have implementation in the parent class but virtual method do.</p>
</li>
</ul>
<h3 id="heading-further-discoveries">Further Discoveries</h3>
<p>Here are some further discoveries I have gathered from various sources that may provide a deeper understanding of C# Abstract:</p>
<ul>
<li><p>The abstract class can't be instantiated.</p>
</li>
<li><p>An abstract class can have a constructor, but never makes the constructor has a <code>public</code> access modifier because abstract class can’t be initialized. Instead use <code>public</code> access modifier make the constructor use <code>protected</code> or <code>internal</code> access modifier instead.</p>
</li>
<li><p>An interface or an abstract class can inherit from another abstract class.</p>
</li>
<li><p>Using a <code>sealed</code> modifier on the abstract class will not cause a compiler error.</p>
  <div data-node-type="callout">
  <div data-node-type="callout-emoji">ℹ</div>
  <div data-node-type="callout-text">Since C# 8, the compiler will display an error message when a <code>sealed</code> modifier is used in an abstract class.</div>
  </div>


</li>
</ul>
<h2 id="heading-reference">Reference</h2>
<ol>
<li><a target="_blank" href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/abstract">C# Abstract – Microsoft</a></li>
</ol>
]]></content:encoded></item></channel></rss>