<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Nidhi Pal on Medium]]></title>
        <description><![CDATA[Stories by Nidhi Pal on Medium]]></description>
        <link>https://medium.com/@nidhii200107?source=rss-0aad5dc097df------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Dd3iddiyTQrsvi0_IPAFdw.jpeg</url>
            <title>Stories by Nidhi Pal on Medium</title>
            <link>https://medium.com/@nidhii200107?source=rss-0aad5dc097df------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 02:44:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nidhii200107/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[C# Basics — Part I: Types, Collections, Interfaces, and Structs]]></title>
            <link>https://medium.com/@nidhii200107/c-basics-part-i-types-collections-interfaces-and-structs-a1f600406dc5?source=rss-0aad5dc097df------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1f600406dc5</guid>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[interview-preparation]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Nidhi Pal]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 15:45:38 GMT</pubDate>
            <atom:updated>2026-10-26T16:14:20.314Z</atom:updated>
            <content:encoded><![CDATA[<p>This article covers essential C# concepts every .NET developer should understand, from value and reference types to collections, properties, interfaces, abstract classes, and structs.</p><p>For each concept, we’ll look at a simple explanation, a practical code example, and key takeaways for interviews and everyday development.</p><h4><strong>1. a. Value </strong>Types:</h4><p>Hold its value directly. A value type assignment copies the value.</p><p><strong>Examples</strong>: int, double, bool, char, struct, and enum.</p><h4><strong>1. b. Reference </strong>Types:</h4><p>Holds a reference to an object.Reference types copy their references, so multiple variables can refer to the same object.</p><p><strong>Examples</strong>: string, arrays, classes, interfaces, and delegates.</p><p>Strings are reference types, but immutable. Reassigning doesn’t change value of a variable.</p><p><strong>Note</strong>:<br>string? allows NULL<br>?? provides NULL fallback value<br>?. safely access a member / prevent unsafe member access</p><pre><br>using System;<br><br>bool first = true;<br>bool second = false;<br><br>// Value types store their values directly.<br>// Assigning one value-type variable to another copies the value.<br>first = second;<br><br>Console.WriteLine(<br>    $&quot;Value types: first={first}, second={second}&quot;);<br><br>// Reference-type variables hold references to objects.<br>// Assigning one reference variable to another copies the reference,<br>// so both variables point to the same object.<br>var firstEmployee = new Employee { Name = &quot;John&quot; };<br>var secondEmployee = firstEmployee;<br><br>secondEmployee.Name = &quot;Doe&quot;;<br><br>Console.WriteLine(<br>    $&quot;Reference types: firstEmployee={firstEmployee.Name}&quot;);<br><br>Console.WriteLine(<br>    $&quot;Reference types: secondEmployee={secondEmployee.Name}&quot;);<br><br>// Nullable value types can store either a value or null.<br>// int? is shorthand for Nullable&lt;int&gt;.<br>int? yearsOfExperience = null;<br><br>// The ?. operator returns null when the nullable value has no value.<br>// The ?? operator provides a fallback when the result is null.<br>Console.WriteLine(<br>    $&quot;\nNullable value: {yearsOfExperience?.ToString() ?? &quot;not supplied&quot;}&quot;);<br><br>yearsOfExperience = 3;<br><br>Console.WriteLine($&quot;Nullable value: {yearsOfExperience}&quot;);<br><br>// Nullable reference annotations enable compile-time nullability analysis.<br>// string? indicates that the variable is allowed to contain null.<br>string? nickname = null;<br><br>// The ?? operator returns the fallback string when nickname is null.<br>Console.WriteLine(<br>    $&quot;Nullable reference: {nickname ?? &quot;no nickname&quot;}&quot;);<br><br>// The ?. operator accesses a member only when its receiver is not null.<br>// Otherwise, the expression evaluates to null.<br>nickname = &quot;Ash&quot;;<br><br>// Check for null before accessing the Length property.<br>if (nickname is not null)<br>{<br>    Console.WriteLine($&quot;Nickname length: {nickname.Length}&quot;);<br>}<br><br>class Employee<br>{<br>    // Initialize Name with an empty string to avoid an uninitialized value.<br>    public string Name { get; set; } = string.Empty;<br>}<br>// Expected output<br>Value types: first=False, second=False<br>Reference types: firstEmployee=Doe<br>Reference types: secondEmployee=Doe<br>Nullable value: not supplied<br>Nullable value: 3<br>Nullable reference: no nickname<br>Nickname length: 3</pre><p><strong><em>Why is string a reference type if strings are immutable?</em></strong><br>Because both are independent characteristics. A <strong>reference type</strong> describes how a variable refers to an object where as <strong>Immutability </strong>means the objects content cannot be changed after creation, they can be reassigned.</p><h4><strong>2. StringBuilder</strong></h4><p>StringBuilder : It is used to modify strings efficiently when performing many changes, because it avoids creating new string object for every modification in typical usage. It is mutable.</p><pre>using System.Text;<br>StringBuilder sb = new StringBuilder(&quot;Hello&quot;);<br><br>sb.Append(&quot; World&quot;); <br>Console.WriteLine(sb.ToString());//Hello World<br><br>sb.Insert(5, &quot;,&quot;); <br>Console.WriteLine(sb); // Hello, World<br><br>sb.Replace(&quot;World&quot;, &quot;C#&quot;);<br>Console.WriteLine(sb); // Hello, C#<br><br>sb.Remove(7, 2);<br>Console.WriteLine(sb); // Hello,<br><br>// Use string for ordinary string operations and StringBuilder when repeatedly appending,<br>// inserting, or replacing content, especially inside loops.</pre><h4><strong>3. a. Difference between array and list.</strong></h4><p>An array has a fixed length after creation. List&lt;T&gt; can grow dynamically and provides methods such as Add() and Remove().</p><h4><strong>4. Five important types of Collection</strong>:</h4><ol><li><strong><em>List</em>&lt;T&gt;</strong>: Stores an ordered sequence of elements and allows duplicates(same as vector in c++), no fixed size.</li></ol><pre>List&lt;string&gt; names = new List&lt;string&gt;();<br>names.Add(&quot;Riya&quot;);<br>names.Add(&quot;Diya&quot;);<br>Console.WriteLine(names.Count);  // output: 2</pre><p><strong>2. <em>Dictionary</em>&lt;TKey, TValue&gt;</strong>: Stores key-value pairs, each key must be unique. Eg: {101: “Asha” , 102: “Riya”}</p><pre>Dictionary&lt;int, string&gt; employees = new Dictionary&lt;int, string&gt;()<br>{<br>  {101, &quot;Riya&quot;},<br>  {102, &quot;Diya&quot;}<br>};</pre><p><strong>3. <em>HashSet</em>&lt;T&gt;:</strong> Stores unique elements and is useful for removing duplicates or checking membership.</p><pre>HashSet&lt;int&gt; numbers = new() {1,2,2,3 };<br>Console.WriteLine(numbers.Count); //3</pre><p><strong>4. <em>Queue</em>&lt;T&gt;:</strong> Stores elements, follows FIFO (First In, First Out). Queue.Peek() reads the front without removing it where as Queue.Dequeue() remove the front and return it.</p><pre>Queue&lt;string&gt; queue = new();<br>queue.Enqueue(&quot;A&quot;);<br>queue.Enqueue(&quot;B&quot;);<br>Console.WriteLine(queue.Peek()); // A<br>Console.WriteLine(queue.Dequeue()); // A<br>Console.WriteLine(queue.Peek()); // B</pre><p><strong>5. <em>Stack</em>&lt;T&gt;:</strong> Stores elements, follows LIFO (Last In, First Out). Push adds an element, Peek reads the top element without removing it, Pop removes and returns the top element.</p><pre>Stack&lt;int&gt; stack = new();<br>stack.Push(10);<br>stack.Push(20);<br><br>Console.WriteLine(stack.Peek()); // 20<br>Console.WriteLine(stack.Pop()); // 20<br>Console.WriteLine(stack.Peek()); // 10</pre><p><strong>Distinguish </strong><strong>var from </strong><strong>dynamic</strong></p><p>var: Type is determined at compile time.<br>dynamic: Member and operation checking is deferred until runtime.</p><pre>//var example:<br>var number = 10;<br>Console.WriteLine(number); // Output: 10<br>number = 20; // Reassigning the variable<br>Console.WriteLine(number); // Output: 20 Valid<br>number = &quot;Hello&quot;; // Invalid, as &#39;number&#39; is of type int<br>//dynamic example:<br>dynamic number = 10;<br>Console.WriteLine(number); // Output: 10<br>number = 20; // Reassigning the variable<br>Console.WriteLine(number); // Output: 20    <br>number = &quot;Hello&quot;; // Valid, as &#39;number&#39; is of type dynamic<br>Console.WriteLine(number); // Output: Hello</pre><p><strong><em>Properties vs fields</em></strong>:<br>A property provides controlled access to a value through get and set. <br>A field stores the value directly.<br>private set means callers outside the class cannot assign the salary.<br>get allows callers to read it.</p><pre>private decimal _salary;<br>public decimal Salary<br>{<br>get {return _salary};<br>private set{<br>if(value&lt;0)<br>  throw new ArgumentException(&quot;Salary cannot be negative&quot;);<br>_salary = value;<br>}<br>}<br>//Use an explicit property when you need validation, transformation, logging, or other behavior.<br>public string Name{get;set;}<br>//auto-implemented property when no additional validation or behavior is needed.<br>Read-only data<br>public string EmployeeId {get;}<br>public Employee(string id){<br>EmployeeId = id;<br>}<br>//This property can be assigned in its constructor but cannot be reassigned by ordinary external</pre><p><strong>Interface</strong>: It defines a set of members that a class must implement when it choses to implement that interface. It allows different classes to provide their own implementations of the same functionality.<br>1. An interface defines the members that implementing classes must provide. <br>2. It helps us achieve loose coupling by allowing a component to depend on an abstraction rather than a specific implementation. <br>3. In .NET, interfaces are commonly used with dependency injection, unit testing, and applications that support multiple implementations of the same functionality.</p><pre>Real life example: Different payment methods - UPI, credit, debit - all need to make payments, but differently<br><br>IPayment upiPayment = new UpiPayment();<br>upiPayment.Pay(1000); //Paid 1000 using UPI<br><br>IPayment cardPayment  = new CardPayment();<br>cardPayment.Pay(2000); //Paid 2000 using Card<br><br>public interface IPayment<br>{<br>    void Pay(decimal amount);<br>}<br><br>public class UpiPayment : IPayment<br>{<br>    public void Pay(decimal amount)<br>    {<br>        Console.WriteLine($&quot;Paid {amount} using UPI&quot;);<br>    }<br>}<br><br>public class CardPayment : IPayment<br>{<br>    public void Pay(decimal amount)<br>    {<br>        Console.WriteLine($&quot;Paid {amount} using Card&quot;);<br>    }<br>}</pre><p><strong>Abstract </strong>Class: An abstract class is a base class that cannot be instantiated directly. It provides shared state and implementation for related classes, while allowing derived classes to implement or override behavior that varies between them.<br>1. It provides common base for related classes.<br>2. It allows us to reuse shared properties &amp; methods while defining abstract methods for behavior that derived classes must implement. <br>3. I would use it when related types share common state or functionality, but some operations require different implementations.</p><pre><br>//Real life example: An organization has permanent employees and contractors, both have common details such as employee name, but thier salary calculations differ.<br>Employee employee = new PermanentEmployee(&quot;John Doe&quot;, 50000);<br>employee.DisplayName(); // Output: Employee Name: John Doe<br>Console.WriteLine($&quot;Salary: {employee.CalculateSalary()}&quot;); // Output: Salary: 50000<br><br>public abstract class Employee<br>{<br>    public string Name {get; set;}<br>    protected Employee(string name)<br>    {<br>        Name = name;<br>    }<br>    public abstract decimal CalculateSalary();<br>    public void DisplayName()<br>    {<br>        Console.WriteLine($&quot;Employee Name: {Name}&quot;);<br>    }<br>}<br>public class PermanentEmployee : Employee<br>{<br>    public decimal BasicSalary {get; set;}<br>    public PermanentEmployee(string name, decimal basicSalary) : base(name)<br>    {<br>        BasicSalary = basicSalary;<br>    }<br>    public override decimal CalculateSalary()<br>    {<br>        return BasicSalary;<br>    }<br>}</pre><p><strong>Struct</strong>: A struct is a value type in c#. When a struct instance is assigned to another variable, its value is copied. Structs are generally suitable for small datatypes that represent values rather than objects with independent identity.</p><pre>// real life eg:graphical application represents a point using X and Y cordinates. When one point is copied, modfying the copy should not change the original point<br>Point point1 = new Point(10, 20);<br>Point point2 = point1;<br>point2.X = 30;<br>Console.WriteLine($&quot;Point 1: X = {point1.X}&quot;); // Output: Point 1: X = 10<br>Console.WriteLine($&quot;Point 2: X = {point2.X}&quot;); // Output: Point 2: X = 30<br>public struct Point<br>{<br>    public int X;<br>    public int Y;<br>    public Point(int x, int y)<br>    {<br>        X = x;<br>        Y = y;<br>    }<br>}</pre><p><strong>How does class and struct differ?</strong><br>A struct is a value type used to represent small, value-like data. Assigning a struct to another variable copies its value, unlike a class assignment, which copies the object reference.<br>I would generally choose a struct for small types such as cordinates or measurements to avoid unexpected copying-related issues.</p><p><strong>Enum: </strong>An enum (enumeration) is a value type that defines a set of named constants. <br>By default, enum values use the underlying type int, and values are assigned starting from zero.</p><pre><br>// Real life example: An order-management system may have following states: Pending - order has been created but is not yet processed. Executed - the order has been successfully executed. Cancelled - order was cancelled<br>using System;<br>using System.Net;<br><br>public enum OrderStatus<br>{<br>    Pending, // 0 <br>    Executed, // 1 <br>    Cancelled, // 2<br>    Rejected // 3<br>}<br>public class Order<br>{<br>    public string OrderId {get; set;}<br>    public OrderStatus Status{get; set;}<br>}<br>public class Program<br>{<br>    public static void Main(string[] args)<br>    {<br>        Order order = new Order<br>        {<br>            OrderId = &quot;ORD101&quot;,<br>            Status = OrderStatus.Pending<br>        };<br><br>        Console.WriteLine(order.Status);<br><br>        if(order.Status == OrderStatus.Pending)<br>        {<br>            Console.WriteLine(&quot;Order is waiting for processing.&quot;);<br>        }<br>    }<br>}</pre><p><strong>Delegates:</strong> Delegate is a <em>type-safe</em> reference to a method, we can store a method in a delegate variable and call that method through the delegate.<br>The assigned method must have a compatible return type and parameter list. This is called type safety. <br>Types of delegates:<br>i) Single</p><pre>Real-life eg: Imagine an order-processing application. When an order is completed, you want to:<br>// Send a notification, Write an audit log, Update some compatible signature.<br>// The order processing code shouldn&#39;t need to know the internal implementation of every action. It can call a delegate, and the method assigned to that delegate determines what happens.<br>using System;<br>public delegate void NotificationHandler(string message);<br>// method accept 1 string parameter, must return void, any compatible method can be assigned to this delegate.<br>public class Program<br>{<br>    static void SendEmail(string message)<br>    {<br>        Console.WriteLine(&quot;Email: &quot;+ message);<br>    }<br>    static void SendSms(string message)<br>    {<br>        System.Console.WriteLine(&quot;SMS: &quot;+ message);<br>    }<br>    public static void Main()<br>    {<br>        NotificationHandler notify  = SendEmail;<br>        notify(&quot;Your order ahs been placed.&quot;);<br><br>        notify = SendSms;<br>        notify(&quot;Your order has been placed&quot;);<br>    }<br>    //Output: <br>    //Email: Your order has been placed<br>    //SMS: Your order has been placed<br>}</pre><p>Q. What happens if an exception occurs and no matching catch block exists?<br>The exception propagates up the call stack. If it remains unhandled, the operation or application may terminate.<br>Q. Does finally always execute?<br>It normally executes when control leaves the try/catch construct, including on return or exception propagation. Process termonation, certain runtime failures, or abrupt shutdown can prevent it.<br>Q. Why use async file operations in ASP.NET Core?<br>They avoid blocking thread while waiting for file I/O, helping server resources remain available for other work.<br>Q. What is the difference between throw and throw ex?<br>Inside a catch block, throw; preserves the original stack trace. throw ex; resets the stack trace again.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1f600406dc5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Level Up Your Coding: The Core Pillars of OOPs Simplified]]></title>
            <link>https://medium.com/@nidhii200107/level-up-your-coding-the-core-pillars-of-oops-simplified-b2584b3175e0?source=rss-0aad5dc097df------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2584b3175e0</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[object-oriented-paradigm]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Nidhi Pal]]></dc:creator>
            <pubDate>Thu, 22 Oct 2026 19:46:28 GMT</pubDate>
            <atom:updated>2026-10-26T16:36:10.204Z</atom:updated>
            <content:encoded><![CDATA[<h3>OOP’s Concept:</h3><p><strong>Class </strong>: We create a class to group related data and behavior into a single logical unit, making code easier to maintain, reuse and extend.</p><p><strong>Encapsulation</strong>: Protect data and control how it is accessed or modified. Protects an object’s internal state by restricting direct access and exposing controlled operations. In c sharp I use private fields, properties, and access modifiers to enforce business rules and maintain valid object state.<br>When to use encapsulation:<br>1. Protect account balances, employee salaries, order statuses, and other business-critical state.<br>2. Validate data before updating it.<br>3. Prevent invalid state transitions.<br>4. Hide implementation details so internal code can change without breaking callers.</p><pre>//For example, a bank account should not allow anyone to set its balance to a negative value arbitrarilly.<br>public class BankAccount<br>{<br>private decimal _balance;<br>public string AccountHolder {get; private set;}<br>public decimal Balance{<br>get { return _balance;}<br>}<br>public BankAccount(string accountHolder, decimal initialBalance){<br>{<br>if(initialBalance &lt; 0)<br>throw new ArgumentException(&quot;Initial balance cannot be negative&quot;);<br>AccountHolder= accountHolder;<br>_balance = initialBalance;<br>}<br>public void Deposit (decimal amount){<br>if(amount&lt;0)<br>throw new ArgumentException(&quot;Amount must be positive&quot;);<br>_balance += amount;<br>}<br>public bool Withdraw(decimal amount){<br>if(amount&lt;=0 || amount&gt;_balance)<br>return false;<br>_balance -= amount;<br>return true;<br>}<br>}<br>//private decimal _balance: external code cannot modify the field directly.<br>//public decimal Balance: allows reading balance, but not assigning to it.<br>//private set: only the class itself can set AccountHolder<br>BankAccount account = new BankAccount (&quot;John&quot;, 1000);<br>account.Deposit(500);<br>account.Withdraw(200);<br><br>Console.WriteLine(account.balannce); //1300<br>//account._balance = -500 compilation error<br>//account.Balance = -500 compilation error</pre><p><strong>Inheritance</strong>: Create a new class based on existing class.<br>It promotes code reuse and extensibility by allowing a derived class to reuse and specialize a base class. I use it when there is-a relationship, while considering composition for more flexible designs.<br>1. Constructors are not inherited, although derived constructors can call base constructors.<br>2. Private members are not directly accessible in derived classes, can be marked sealed to prevent other classes from inhriting from it.<br>3. A class can inherit from an abstract class, but it must implement the inherited abstract members unless it is itself abstract.</p><pre>//example: employee management system<br>//Imagine our app has 2 kinds of employees: developers and managers. Both have an ID, a name, and a method to display their details, but each has additionals responsibilities.<br>&lt;-- Single-level Inheritance --&gt;<br>public class Employee{<br>  public int Id {get; set;}<br>  public string Name {get; set;}<br>  public void DisplayDetails(){<br>    Console.WriteLine($&quot;{Id} : {Name}&quot;);<br>  }<br>}<br>public class Developer : Employee{<br>  public string ProgLang {get; set;}<br>  public void WriteCode(){<br>    Console.WriteLine(&quot;Developer is writing code&quot;);<br>  }<br>}<br>public class Manager: Employee{<br>  public int Teamsize {get; set;}<br>  public void ConductMeeting(){<br>    Console.WriteLine(&quot;Manager is conducting a meeting&quot;);<br>  }<br>}<br>Developer dev = new Developer { Id=101, Name=&quot;John&quot;, ProgLang=&quot;C#&quot; };<br>dev.DisplayDetails(); //101 : John - Inherited method<br>dev.WriteCode(); //Developer is writing code - Developer specific method<br>--&gt; Mutli-level Inheritance --&gt;<br>class Animal {}<br>class Mammal : Animal {}<br>class Dog : Mammal {}<br>--&gt; Hierarchical Inheritance --&gt;<br>class Employee {}<br>class Developer : Employee {}<br>class Manager : Employee {}<br>--&gt; Multiple Inheritance --&gt;<br>//C#class does not allow to inherit from multiple classes<br>class c : A, B {} // if A &amp; B are classes, allows a class to inherit multiple interfaces<br>interface Ilogger{<br>  void Log(string message);<br>}<br>interface IEmailService{<br>  void sendEmail(string message);<br>}<br>class NotificationService : Ilogger, IEmailService {<br>  public void Log(string message) {<br>    Console.WriteLine(message);<br>  }<br>  public void SendEmail(string message) {<br>    Console.WriteLine($&quot;Email: {message}&quot;);<br>   }<br>}<br>// Use base to access a base-class constructor or a base-class implementation.<br>public class Employee {<br>  public string Name {get; }<br>  public Employee (string name){<br>    Name = name;<br>  }<br>  public virtual void Work() {<br>    Console.WriteLine(&quot;Employee is Working&quot;);<br>  }<br>}<br>public class Developer : Employee<br>{ public Developer (string name) : base(name){}<br>  public override void Work() {<br>    base.Work();<br>    Console.WriteLine(&quot;Developer is writing code&quot;);<br>  }<br>}<br>:base(name) - invokes parent constructor<br>base.Work() - invokes base implementation.<br>override - allows derived class to provide its own implementation of a virtual method.</pre><p><strong>Polymorphism</strong>: Same interface or base type can produce different behavior. It lets callers use a common base class or interface while different implementations perform their own behavior. I use method overloading for compile-time selection and overriding or interfaces for runtime flexibility, such as supporting multiple payment providers.</p><pre>// It is of 2 types:<br>// Compile-time Polymorphism: method overloading &amp; operator overloading.<br>// Runtime Polymorphism: method overriding using virtual and override, or implementations through interfaces.<br>// Method overloading: means multiple methods have the same name but different parameter lists.<br>public class Calculator{<br>  public int Add(int a, int b){<br>    return a+b;<br>  public int Add(int a, int b, int c){<br>    return a+b+c;<br>  }<br>  public double Add(double a, double b){<br>    return a+b;<br>  }<br>Calculator calc = new Calculator();<br>Console.WriteLine(calc.Add(2,3)); // 5<br>Console.WriteLine(calc.Add(2,3,4)); //9<br>Console.WriteLine(calc.Add(2.5,3.5)); //6.0<br>// Changing number of parameters, parameter types, parameter orders, can create overload.<br>// Changing only return type cannot create a valid overload. For example:<br>int Calculate(int x) =&gt; x;<br>double Calculate(int x) =&gt;x;</pre><p><strong>Abstraction</strong>: Expose what an object does while hiding implementations details. <br>2. Abstract class cannot be instantiated directly.<br>3. Each derived class must implement abstract class method.<br>4. An abstract class can have constructors, fields, properties, concrete methods, and abstract methods and non-abstract methods.</p><pre>//In C#, abstraction is implemented using: 1.Abstract classes 2. Interfaces.<br>// 1. Abstraction using abstract classes<br>// Abstract class can define a common contract &amp; optionally provide shared implementation.<br>public abstract class Notification{<br>  public void ValidateMessage(string message){<br>    if(string.IsNullOrWhiteSpace(message))<br>      throw new ArgumentException(&quot;Message cannot be empty&quot;);<br>   }<br>  public abstract void Send(string message);<br>}<br>public class EmailNotification : Notification{<br>  public override void Send(string message){<br>    ValidateMessage(message);<br>    Console.WriteLine(&quot;Sending email: &quot; + message);<br>  }<br>}<br>public class SmsNotification : Notification{<br>  public override void Send(string message){<br>    Validate(message);<br>    Console.WriteLine(&quot;Sending SMS: &quot; +message);<br>  }<br>}<br><br>Notificaton notification = new EmailNotification();<br>notification.Send(&quot;Welcome!&quot;);<br><br>Notificaton notification = new SmsNotification();<br>notification.Send(&quot;Your otp is 1234&quot;);<br><br>// 2. Abstraction using interfaces<br>// An interface defines a contract that implementing types must satify.<br>public interface ILogger<br>{<br>    void Log(string message);<br>}<br>public class FileLogger : ILogger<br>{<br>    public void Log(string message)<br>    {<br>        Console.WriteLine($&quot;Logging to a file: {message}&quot;);<br>    }<br>} <br>public class ConsoleLogger : ILogger<br>{<br>    public void Log(string message)<br>    {<br>        Console.WriteLine($&quot;Logging to the console: {message}&quot;);<br>    }<br>}<br>//Service can depend on interface:<br>public class OrderService<br>{<br>    private readonly ILogger _logger;<br>    public OrderService(ILogger logger)<br>    {<br>        _logger = logger;<br>    }<br><br>    public void PlaceOrder()<br>    {<br>        _logger.Log(&quot;Order has been placed.&quot;);<br>    }<br>}<br><br><br>public class Program<br>{<br>    public static void Main(string[] args)<br>    {<br>        // using Filelogger<br>        ILogger filelogger = new FileLogger();<br>        OrderService orderService1 = new OrderService(filelogger);<br>        orderService1.PlaceOrder(); // Logging to a file: Order has been placed.<br>    }<br>}</pre><p>An <strong>abstract class</strong> can define a common contract and optionally provide shared implementation.</p><p><strong>Difference between <em>Property </em>and <em>Constructor</em></strong>:<br><em>Property</em>: // stores or exposes object’s information<br>1. Represents or exposes object data.<br>2. Can have get and set accessors.<br>3. Can be accessed after object creation.<br>4. Doesnot have a return type.<br><em>Constructor</em>: // gives the object its initial values<br>1. Initializes a new object.<br>2. Has the same name as that of class.<br>3. Runs during object creation.<br>4. Does not have a return type.</p><p><strong><em>Difference between abstract and override keywords:</em></strong><br><em>abstract</em>:<br>1. Declares behavior that must be implemented by a concrete derived class.<br>2. Has no method body.<br><em>override</em>:<br>1. Provide or replaces an inherited virtual or abstract method implementation.<br>2. Has a method body.</p><h4><strong>OOP Implementation: Order Management Example in C#</strong></h4><pre><br>1\. Class &amp; Object: Create an `Order` class with `Symbol`, `Quantity`, and a constructor to initialize order objects.<br><br>2\. Encapsulation: Restrict direct modification of `Quantity` using a private setter and validate positive quantities in the constructor.<br><br>3\. Abstraction: Declare `Order` as an abstract class with an abstract `CalculateValue()` method.<br><br>4\. Inheritance: Create `MarketOrder` and `LimitOrder` classes that inherit common properties and validation from `Order`.<br><br>5\. Polymorphism: Override `CalculateValue()` in both derived classes to implement type-specific calculations.<br><br>6\. Testing: Store both order types in a `List&lt;Order&gt;` and use a `foreach` loop to demonstrate runtime polymorphism.<br><br>Note: This is a simplified OOP learning example, not a complete trading system.<br><br>using System;<br>//using top-level statements in C# 9.0 and later, we can write code directly without needing a main method or class. This is useful for small programs or scripts.<br>// Order order = new MarketOrder(&quot;MSFT&quot;, 10);<br>// decimal value = order.CalculateValue(410);<br><br>// Order order2 = new LimitOrder(&quot;SFTP&quot;, 10, 420);<br>// decimal value2 = order2.CalculateValue(400);<br>List&lt;Order&gt; orders = new List&lt;Order&gt;<br>{<br>    new MarketOrder(&quot;MSFT&quot;, 10),<br>    new LimitOrder(&quot;SFTP&quot;, 10, 400)<br>};<br><br>// Console.WriteLine($&quot;Symbol: {order.Symbol}&quot;);<br>// Console.WriteLine($&quot;Quantity: {order.Quantity}&quot;);<br>// Console.WriteLine($&quot;Value: {value}&quot;);<br>foreach (var item in orders)<br>{<br>    Console.WriteLine($&quot;Symbol: {item.Symbol}, Quantity: {item.Quantity}, Value: {item.CalculateValue(410)}&quot;);<br>}<br><br>public abstract class Order<br>{<br>    public string Symbol {get; set;}<br>    public int Quantity {get; private set;}<br>    protected Order(string symbol, int quantity)<br>    {<br>        Symbol = symbol;<br>        if(quantity &lt;= 0)<br>        {<br>            throw new ArgumentException(&quot;Quantity must be positive&quot;);<br>        }<br>        Quantity = quantity;<br>        Console.WriteLine(&quot;base constructor called&quot;);<br>    }<br><br>    public abstract decimal CalculateValue(decimal price);<br>    // public static int Main(string[] args) // this is not required for mordfern c#<br>    // {<br>        // var order = new Order (&quot;MSFT&quot;, 10);<br>        // Console.WriteLine($&quot;Symbol: {order.Symbol}, Quantity: {order.Quantity}&quot;);<br>    //     return 0;<br>    // }<br><br>}<br><br>public class MarketOrder : Order<br>{<br>    public MarketOrder(string symbol, int quantity) : base(symbol, quantity)<br>    {<br>        Console.WriteLine(&quot;child constructor called&quot;);<br>    }<br>    public override decimal CalculateValue(decimal price)<br>    {<br>        return Quantity * price;<br>    }<br>}<br><br>public class LimitOrder : Order<br>{<br>    public decimal LimitPrice {get; private set;}<br>    public LimitOrder(string symbol, int quantity, decimal limitPrice) : base (symbol, quantity)<br>    {<br>        if(limitPrice &lt;= 0)<br>        {<br>            throw new ArgumentException(&quot;Limit price must be positive&quot;);<br>        }<br>        LimitPrice = limitPrice;<br>    }<br>    public override decimal CalculateValue(decimal price)<br>    {<br>        return Quantity * LimitPrice;<br>    }<br>}</pre><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2584b3175e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Essential .NET Design Patterns Every Developer Needs]]></title>
            <link>https://medium.com/@nidhii200107/essential-net-design-patterns-every-developer-needs-47a4e6db8f8e?source=rss-0aad5dc097df------2</link>
            <guid isPermaLink="false">https://medium.com/p/47a4e6db8f8e</guid>
            <category><![CDATA[c-sharp-language]]></category>
            <category><![CDATA[dot-net-core]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Nidhi Pal]]></dc:creator>
            <pubDate>Sun, 04 Oct 2026 20:25:35 GMT</pubDate>
            <atom:updated>2026-10-26T17:12:00.535Z</atom:updated>
            <content:encoded><![CDATA[<h3>Design Patterns in .NET</h3><p>Design patterns are <strong>reusable approaches to commonly occurring software design problems</strong>.</p><p>They are not ready-made code that you copy into every project. Instead, they provide a proven way to structure classes, objects, and their interactions.</p><p>In .NET development, design patterns are especially useful when building <strong>ASP.NET Core APIs, microservices, enterprise applications, and distributed systems</strong>.</p><h3>Types of Design Patterns</h3><p>Design patterns are generally divided into three categories:</p><h3>1. Creational Design Patterns</h3><p>These deal with <strong>object creation</strong>.</p><p>Examples:</p><ul><li>Singleton</li><li>Factory</li><li>Builder</li><li>Prototype</li><li>Factory Method</li><li>Abstract Factory</li></ul><h3>2. Structural Design Patterns</h3><p>These deal with <strong>how classes and objects are composed</strong>.</p><p>Examples:</p><ul><li>Adapter</li><li>Facade</li><li>Decorator</li><li>Composite</li><li>Proxy</li><li>Flyweight</li><li>Bridge</li></ul><h3>3. Behavioral Design Patterns</h3><p>These deal with <strong>communication and responsibility between objects</strong>.</p><p>Examples:</p><ul><li>Strategy</li><li>Observer</li><li>Command</li><li>Chain of Responsibility</li><li>Iterator</li><li>State</li><li>Template Method</li><li>Mediator</li><li>Visitor</li><li>Memento</li></ul><h3>1. Singleton Design Pattern</h3><p>The Singleton pattern ensures that <strong>only one instance of a class exists</strong> and provides a way to access that instance.</p><h3>Real-world example</h3><p>Imagine an application having a configuration manager.</p><p>You don’t want every part of the application to create a separate configuration manager.</p><p>Instead:</p><pre>Application<br>    |<br>    +---- ConfigurationManager<br>    |<br>    +---- Service A<br>    |<br>    +---- Service B</pre><p>All components use the <strong>same instance</strong>.</p><h3>Simple C# example</h3><pre>public sealed class ConfigurationManager<br>{<br>    private static readonly ConfigurationManager _instance =<br>        new ConfigurationManager();<br>    private ConfigurationManager()<br>    {<br>    }<br>    public static ConfigurationManager Instance<br>    {<br>        get { return _instance; }<br>    }<br>    public string Environment =&gt; &quot;Production&quot;;<br>}</pre><p>Usage:</p><pre>var config1 = ConfigurationManager.Instance;<br>var config2 = ConfigurationManager.Instance;<br>Console.WriteLine(<br>    ReferenceEquals(config1, config2)<br>);</pre><p>Output:</p><pre>True</pre><p>Both variables point to the <strong>same object</strong>.</p><h3>Lazy Singleton</h3><p>Sometimes we don’t want to create the object until it is actually needed.</p><p>We can use Lazy&lt;T&gt;:</p><pre>public sealed class Logger<br>{<br>    private static readonly Lazy&lt;Logger&gt; _instance =<br>        new Lazy&lt;Logger&gt;(() =&gt; new Logger());<br>    private Logger()<br>    {<br>    }<br>    public static Logger Instance =&gt; _instance.Value;<br>    public void Log(string message)<br>    {<br>        Console.WriteLine(message);<br>    }<br>}</pre><p>Usage:</p><pre>Logger.Instance.Log(&quot;Application started&quot;);<br>// The Logger object is created only when:<br>// Logger.Instance is accessed for the first time.</pre><h3>Singleton in ASP.NET Core</h3><p>In modern ASP.NET Core applications, you normally don’t manually implement Singleton.</p><p>Instead, use the built-in Dependency Injection container:</p><pre>  builder.Services.AddSingleton&lt;ICacheService, CacheService&gt;();</pre><p>ASP.NET Core then maintains one instance of CacheService for the application.</p><h3>Singleton vs Static Class</h3><p>These two concepts are often confused.</p><h3>Static class</h3><pre>public static class MathHelper<br>{<br>    public static int Add(int a, int b)<br>    {<br>        return a + b;<br>    }<br>}</pre><p>You cannot do:</p><pre>var helper = new MathHelper(); // ❌</pre><p>You simply call:</p><pre>MathHelper.Add(10, 20);</pre><h3>Singleton</h3><p>A Singleton is a <strong>normal object</strong>, but only one instance is allowed.</p><pre>var logger = Logger.Instance;</pre><p>This means a Singleton can be treated as an object.</p><p>For example:</p><pre>public void Process(Logger logger)<br>{<br>    logger.Log(&quot;Processing...&quot;);<br>}</pre><p>You can pass the Singleton instance:</p><pre>Process(Logger.Instance);</pre><p>But you cannot pass a static class as an object:</p><pre>public void Process(MathHelper helper)<br>{<br>}</pre><p>because MathHelper is not an object instance.</p><h3>Important difference</h3><pre>Static Class<br>     ↓<br>No object instance<br><br>Singleton<br>     ↓<br>One object instance</pre><p>This distinction becomes especially important when using <strong>interfaces and Dependency Injection</strong>.</p><p>For example:</p><pre>public interface ILogger<br>{<br>    void Log(string message);<br>}</pre><p>A Singleton implementation can implement this interface:</p><pre>public class Logger : ILogger<br>{<br>    public void Log(string message)<br>    {<br>        Console.WriteLine(message);<br>    }<br>}</pre><p>and can be registered:</p><pre>builder.Services.AddSingleton&lt;ILogger, Logger&gt;();</pre><p>This makes Singleton much more flexible in application architecture.</p><h3>2. Builder Design Pattern</h3><p>The Builder pattern is useful when an object has <strong>many optional properties</strong> or when construction involves multiple steps.</p><p>Imagine creating a user:</p><pre>var user = new User(<br>    &quot;Nidhi&quot;,<br>    &quot;nidhi@example.com&quot;,<br>    25,<br>    &quot;Pune&quot;,<br>    true,<br>    &quot;Developer&quot;<br>);</pre><p>This becomes difficult to understand.</p><p>Which argument is true?</p><p>Which one is the city?</p><p>Instead, we can use the Builder pattern.</p><h3>Product</h3><pre>public class User<br>{<br>    public string Name { get; set; }<br>    public string Email { get; set; }<br>    public int Age { get; set; }<br>    public string City { get; set; }<br>    public string Role { get; set; }<br>}</pre><h3>Builder</h3><pre>public class UserBuilder<br>{<br>    private readonly User _user = new User();<br>    public UserBuilder SetName(string name)<br>    {<br>        _user.Name = name;<br>        return this;<br>    }<br>    public UserBuilder SetEmail(string email)<br>    {<br>        _user.Email = email;<br>        return this;<br>    }<br>    public UserBuilder SetAge(int age)<br>    {<br>        _user.Age = age;<br>        return this;<br>    }<br>    public UserBuilder SetCity(string city)<br>    {<br>        _user.City = city;<br>        return this;<br>    }<br>    public UserBuilder SetRole(string role)<br>    {<br>        _user.Role = role;<br>        return this;<br>    }<br>    public User Build()<br>    {<br>        return _user;<br>    }<br>}</pre><p>Usage:</p><pre>var user = new UserBuilder()<br>    .SetName(&quot;Nidhi&quot;)<br>    .SetEmail(&quot;nidhi@example.com&quot;)<br>    .SetAge(25)<br>    .SetCity(&quot;Pune&quot;)<br>    .SetRole(&quot;Software Engineer&quot;)<br>    .Build();</pre><p>This is much easier to read.</p><h3>When should you use Builder?</h3><p>Use it when:</p><ul><li>There are many optional properties.</li><li>Object creation involves multiple steps.</li><li>Constructors are becoming difficult to read.</li><li>You want readable object construction.</li></ul><h3>3. Prototype Pattern</h3><p>The Prototype pattern creates a new object by <strong>copying an existing object</strong>.</p><p>There are two important concepts in C#:</p><ul><li>Shallow Copy</li><li>Deep Copy</li></ul><h3>Shallow Copy</h3><p>Suppose we have:</p><pre>public class Employee<br>{<br>    public string Name { get; set; }<br>    public Address Address { get; set; }<br>}<br>public class Address<br>{<br>    public string City { get; set; }<br>}</pre><p>Now:</p><pre>var employee1 = new Employee<br>{<br>    Name = &quot;Nidhi&quot;,<br>    Address = new Address<br>    {<br>        City = &quot;Pune&quot;<br>    }<br>};</pre><pre>var employee2 = employee1;</pre><p>This does <strong>not create a new Employee object</strong>.</p><p>Both variables point to the same object.</p><pre>employee1 ───────┐<br>                 ↓<br>              Employee<br>                 ↑<br>employee2 ───────┘</pre><p>For a shallow copy using MemberwiseClone():</p><pre>var employee2 =<br>    (Employee)employee1.MemberwiseClone();</pre><p>A new Employee object is created, but reference-type fields such as Address still point to the same Address object.</p><h3>Deep Copy</h3><p>A deep copy creates independent objects.</p><pre>var employee2 = new Employee<br>{<br>    Name = employee1.Name,<br>    Address = new Address<br>    {<br>        City = employee1.Address.City<br>    }<br>};</pre><p>Now:</p><pre>employee1<br>   |<br> Employee<br>   |<br> Address<br><br>employee2<br>   |<br> Employee<br>   |<br> Address</pre><p>The Address objects are also different.</p><h3>When is Prototype useful?</h3><p>Prototype can be useful when creating a new object from an existing object is cheaper or easier than constructing it from scratch.</p><h3>4. Dependency Injection</h3><p>Dependency Injection is one of the most important concepts in ASP.NET Core. The basic idea is:</p><blockquote><em>A class should receive the dependencies it needs from outside instead of creating them itself.</em></blockquote><h3>Without Dependency Injection</h3><pre>public class OrderService<br>{<br>    private readonly EmailService _emailService;<br>    public OrderService()<br>    {<br>        _emailService = new EmailService();<br>    }<br>}</pre><p>The OrderService is tightly coupled to EmailService.</p><p>Testing becomes difficult.</p><h3>With Dependency Injection</h3><p>Create an interface:</p><pre>public interface IEmailService<br>{<br>    void SendEmail(string message);<br>}</pre><p>Implementation:</p><pre>public class EmailService : IEmailService<br>{<br>    public void SendEmail(string message)<br>    {<br>        Console.WriteLine(message);<br>    }<br>}</pre><p>Now inject it:</p><pre>public class OrderService<br>{<br>    private readonly IEmailService _emailService;<br>    public OrderService(IEmailService emailService)<br>    {<br>        _emailService = emailService;<br>    }<br>    public void PlaceOrder()<br>    {<br>        // Order processing<br>        _emailService.SendEmail(&quot;Order placed successfully.&quot;);<br>    }<br>}</pre><p>Register it:</p><pre>builder.Services.AddScoped&lt;IEmailService, EmailService&gt;();</pre><p>ASP.NET Core creates and provides the dependency automatically.</p><h3>Benefits</h3><ul><li>Loose coupling</li><li>Easier unit testing</li><li>Better maintainability</li><li>Easier replacement of implementations</li><li>Supports SOLID principles</li></ul><h3>Types of Dependency Injection</h3><h3>1. Constructor Injection</h3><p>Most commonly used:</p><pre>public OrderService(IEmailService emailService)<br>{<br>    _emailService = emailService;<br>}</pre><h3>2. Property Injection</h3><p>Dependency is provided through a property.</p><pre>public IEmailService EmailService { get; set; }</pre><h3>3. Method Injection</h3><p>Dependency is passed to a particular method.</p><pre>public void ProcessOrder(IEmailService emailService)<br>{<br>    emailService.SendEmail(&quot;Order processed&quot;);<br>}</pre><p>In ASP.NET Core applications, <strong>constructor injection is generally the preferred approach</strong>.</p><h3>5. Repository Pattern</h3><p>The Repository pattern abstracts data-access logic.</p><p>Instead of writing database logic directly inside a service:</p><pre>public class UserService<br>{<br>    // SQL/database logic everywhere<br>}</pre><p>we create a repository.</p><pre>public interface IUserRepository<br>{<br>    User GetById(int id);<br>    void Add(User user);<br>}</pre><p>Implementation:</p><pre>public class UserRepository : IUserRepository<br>{<br>    private readonly AppDbContext _context;<br>    public UserRepository(AppDbContext context)<br>    {<br>        _context = context;<br>    }<br>    public User GetById(int id)<br>    {<br>        return _context.Users.Find(id);<br>    }<br>    public void Add(User user)<br>    {<br>        _context.Users.Add(user);<br>    }<br>}</pre><p>Now the service depends on the abstraction:</p><pre>public class UserService<br>{<br>    private readonly IUserRepository _repository;<br>    public UserService(IUserRepository repository)<br>    {<br>        _repository = repository;<br>    }<br>    public User GetUser(int id)<br>    {<br>        return _repository.GetById(id);<br>    }<br>}</pre><p>This separates:</p><pre>Controller<br>    ↓<br>Service<br>    ↓<br>Repository<br>    ↓<br>Database</pre><h3>Important note about EF Core</h3><p>Entity Framework Core already provides many repository-like capabilities through DbSet&lt;T&gt; and DbContext.</p><p>Therefore, adding a custom generic repository on top of EF Core is <strong>not automatically beneficial</strong>. Use it when it provides a genuine architectural advantage rather than simply wrapping every EF Core method.</p><h3>6. Unit of Work Pattern</h3><p>Unit of Work coordinates multiple database operations and commits them as one logical transaction.</p><p>Imagine transferring money:</p><pre>Account A<br>   ↓<br>- ₹100<br><br>Account B<br>   ↓<br>+ ₹100</pre><p>Both operations must succeed.</p><p>If one succeeds and the other fails, we have an inconsistent state.</p><p>A Unit of Work helps treat them as one operation.</p><h3>Example</h3><pre>public interface IUnitOfWork<br>{<br>    IUserRepository Users { get; }<br>    Task SaveChangesAsync();<br>}</pre><p>Implementation:</p><pre>public class UnitOfWork : IUnitOfWork<br>{<br>    private readonly AppDbContext _context;<br>    public IUserRepository Users { get; }<br>    public UnitOfWork(<br>        AppDbContext context,<br>        IUserRepository users)<br>    {<br>        _context = context;<br>        Users = users;<br>    }<br>    public async Task SaveChangesAsync()<br>    {<br>        await _context.SaveChangesAsync();<br>    }<br>}</pre><p>Usage:</p><pre>await unitOfWork.Users.Add(user);<br>await unitOfWork.SaveChangesAsync();</pre><p>In EF Core, DbContext itself already behaves similarly to a Unit of Work by tracking changes and committing them through SaveChanges() / SaveChangesAsync().</p><h3>7. Factory Pattern</h3><p>The Factory pattern centralizes object creation.</p><p>Suppose our application supports multiple payment methods:</p><pre>Credit Card<br>UPI<br>PayPal</pre><p>Instead of writing:</p><pre>if (paymentType == &quot;UPI&quot;)<br>{<br>    // create UPI service<br>}<br>else if (paymentType == &quot;Card&quot;)<br>{<br>    // create Card service<br>}</pre><p>everywhere, we can use a Factory.</p><h3>Interface</h3><pre>public interface IPaymentService<br>{<br>    void Pay(decimal amount);<br>}</pre><p>Implementations:</p><pre>public class UpiPayment : IPaymentService<br>{<br>    public void Pay(decimal amount)<br>    {<br>        Console.WriteLine($&quot;Paid ₹{amount} using UPI&quot;);<br>    }<br>}<br>public class CardPayment : IPaymentService<br>{<br>    public void Pay(decimal amount)<br>    {<br>        Console.WriteLine($&quot;Paid ₹{amount} using Card&quot;);<br>    }<br>}</pre><h3>Factory</h3><pre>public class PaymentFactory<br>{<br>    public IPaymentService Create(string paymentType)<br>    {<br>        return paymentType switch<br>        {<br>            &quot;UPI&quot; =&gt; new UpiPayment(),<br>            &quot;Card&quot; =&gt; new CardPayment(),<br>            _ =&gt; throw new ArgumentException(&quot;Invalid payment type&quot;)<br>        };<br>    }<br>}</pre><p>Usage:</p><pre>var factory = new PaymentFactory();<br>var payment = factory.Create(&quot;UPI&quot;);<br>payment.Pay(1000);</pre><p>Output:</p><pre>Paid ₹1000 using UPI</pre><h3>Why use Factory?</h3><p>The client doesn’t need to know:</p><pre>Which class?<br>How is it created?<br>What constructor does it have?</pre><p>It simply asks:</p><pre>Factory → Give me a payment service</pre><h3>8. Strategy Pattern</h3><p>The Strategy pattern allows us to change an algorithm or behavior <strong>at runtime</strong>.</p><p>Imagine an e-commerce application supporting different discount strategies:</p><pre>Regular Customer → 5%<br>Premium Customer → 10%<br>VIP Customer     → 20%</pre><h3>Strategy interface</h3><pre>public interface IDiscountStrategy<br>{<br>    decimal CalculateDiscount(decimal amount);<br>}</pre><p>Implementations:</p><pre>public class RegularDiscount : IDiscountStrategy<br>{<br>    public decimal CalculateDiscount(decimal amount)<br>    {<br>        return amount * 0.05m;<br>    }<br>}</pre><pre>public class PremiumDiscount : IDiscountStrategy<br>{<br>    public decimal CalculateDiscount(decimal amount)<br>    {<br>        return amount * 0.10m;<br>    }<br>}</pre><p>Context:</p><pre>public class DiscountService<br>{<br>    private readonly IDiscountStrategy _strategy;</pre><pre>    public DiscountService(IDiscountStrategy strategy)<br>    {<br>        _strategy = strategy;<br>    }</pre><pre>    public decimal GetFinalPrice(decimal amount)<br>    {<br>        return amount - _strategy.CalculateDiscount(amount);<br>    }<br>}</pre><p>Usage:</p><pre>var service =<br>    new DiscountService(new PremiumDiscount());</pre><pre>var finalPrice =<br>    service.GetFinalPrice(1000);</pre><pre>Console.WriteLine(finalPrice);</pre><p>Output:</p><pre>900</pre><p>The behavior can be changed without modifying DiscountService.</p><h3>9. Observer Pattern</h3><p>The Observer pattern is useful when one object needs to notify multiple other objects about a change.</p><p>For example:</p><pre>Order Placed<br>     |<br>     +---- Email Service<br>     |<br>     +---- SMS Service<br>     |<br>     +---- Notification Service</pre><p>The Order system doesn’t need to know the internal implementation of each subscriber.</p><h3>Example</h3><pre>public interface IOrderObserver<br>{<br>    void OrderPlaced(int orderId);<br>}</pre><p>Observers:</p><pre>public class EmailNotifier : IOrderObserver<br>{<br>    public void OrderPlaced(int orderId)<br>    {<br>        Console.WriteLine(<br>            $&quot;Email sent for order {orderId}&quot;);<br>    }<br>}</pre><pre>public class SmsNotifier : IOrderObserver<br>{<br>    public void OrderPlaced(int orderId)<br>    {<br>        Console.WriteLine(<br>            $&quot;SMS sent for order {orderId}&quot;);<br>    }<br>}</pre><p>Subject:</p><pre>public class OrderService<br>{<br>    private readonly List&lt;IOrderObserver&gt; _observers = new();</pre><pre>    public void Subscribe(IOrderObserver observer)<br>    {<br>        _observers.Add(observer);<br>    }</pre><pre>    public void PlaceOrder(int orderId)<br>    {<br>        Console.WriteLine(&quot;Order placed&quot;);</pre><pre>        foreach (var observer in _observers)<br>        {<br>            observer.OrderPlaced(orderId);<br>        }<br>    }<br>}</pre><p>Usage:</p><pre>var orderService = new OrderService();</pre><pre>orderService.Subscribe(new EmailNotifier());<br>orderService.Subscribe(new SmsNotifier());</pre><pre>orderService.PlaceOrder(101);</pre><p>Output:</p><pre>Order placed<br>Email sent for order 101<br>SMS sent for order 101</pre><p>In real .NET applications, similar ideas are commonly implemented using <strong>events, messaging systems, or event-driven architectures</strong>.</p><h3>10. CQRS</h3><p>CQRS stands for:</p><p><strong>Command Query Responsibility Segregation</strong></p><p>The main idea is to separate:</p><pre>Commands → Change data</pre><pre>Queries → Read data</pre><p>Instead of having one service responsible for everything:</p><pre>UserService<br>    ↓<br>Create<br>Update<br>Delete<br>Get<br>Search</pre><p>we separate responsibilities:</p><pre>Command Side                 Query Side</pre><pre>CreateUser                   GetUser<br>UpdateUser                   SearchUsers<br>DeleteUser                   GetUsers</pre><h3>Command</h3><pre>public record CreateUserCommand(<br>    string Name,<br>    string Email<br>);</pre><p>Handler:</p><pre>public class CreateUserHandler<br>{<br>    public void Handle(CreateUserCommand command)<br>    {<br>        // Save user to database<br>    }<br>}</pre><h3>Query</h3><pre>public record GetUserQuery(int UserId);</pre><p>Handler:</p><pre>public class GetUserHandler<br>{<br>    public User Handle(GetUserQuery query)<br>    {<br>        // Fetch user from database</pre><pre>        return new User();<br>    }<br>}</pre><p>CQRS becomes particularly useful when read and write workloads have different requirements or when the application has complex domain behavior.</p><p>However, <strong>CQRS is not required for every CRUD application</strong>.</p><h3>Dependency Injection Lifetimes</h3><p>ASP.NET Core provides three common DI lifetimes.</p><h3>Singleton</h3><p>One instance for the application’s service container lifetime.</p><pre>builder.Services.AddSingleton&lt;ICacheService, CacheService&gt;();</pre><p>Good examples:</p><ul><li>Stateless shared services</li><li>Application-wide caches</li><li>Configuration-related services</li></ul><p>Be careful with Singleton services that depend on scoped services.</p><h3>Scoped</h3><p>One instance per HTTP request.</p><pre>builder.Services.AddScoped&lt;IUserRepository, UserRepository&gt;();</pre><p>DbContext is commonly registered as scoped.</p><p>Conceptually:</p><pre>Request 1<br>   ↓<br>Repository Instance A</pre><pre>Request 2<br>   ↓<br>Repository Instance B</pre><h3>Transient</h3><p>A new instance is created whenever the service is requested.</p><pre>builder.Services.AddTransient&lt;IEmailService, EmailService&gt;();</pre><p>Useful for lightweight, stateless services.</p><h3>Putting the Patterns Together</h3><p>A real ASP.NET Core application might look like this:</p><pre>HTTP Request<br>                      ↓<br>                 Controller<br>                      ↓<br>                 Service Layer<br>                      ↓<br>          ┌───────────┴───────────┐<br>          ↓                       ↓<br>       Strategy                Factory<br>          ↓                       ↓<br>    Business Rule           Create Object<br>                                  ↓<br>                             Repository<br>                                  ↓<br>                              DbContext<br>                                  ↓<br>                              Database</pre><p>And Dependency Injection connects these components:</p><pre>ASP.NET Core DI Container<br>          |<br>          +---- Controller<br>          |<br>          +---- Service<br>          |<br>          +---- Repository<br>          |<br>          +---- Strategy<br>          |<br>          +---- Factory</pre><h3>Quick Interview Summary</h3><p>A simple way to remember the most important patterns:<br>A useful mental model is:</p><pre>DI        → How dependencies enter<br>Factory   → How objects are created<br>Builder   → How complex objects are constructed<br>Singleton → How one shared instance is maintained<br>Repository→ How data access is abstracted<br>UoW       → How related DB changes are committed<br>Strategy  → How behavior changes<br>Observer  → How objects get notified<br>CQRS      → How reads and writes are separated</pre><h3>Final Thought</h3><p>Design patterns should not be used simply because they exist.</p><p>The important question is:</p><blockquote><strong><em>What problem am I solving, and does this pattern make the solution simpler, more maintainable, or more flexible?</em></strong></blockquote><p>For example, don’t introduce CQRS into a simple CRUD application just because CQRS is popular.</p><p>Similarly, don’t create a Singleton manually when ASP.NET Core’s Dependency Injection container can manage the lifetime for you.</p><p>Good software design is not about using <strong>more patterns</strong>.</p><p>It is about using the <strong>right pattern at the right time</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47a4e6db8f8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sql Practice Sheet 1]]></title>
            <link>https://medium.com/@nidhii200107/sql-practice-sheet-1-6f88df224ca6?source=rss-0aad5dc097df------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f88df224ca6</guid>
            <dc:creator><![CDATA[Nidhi Pal]]></dc:creator>
            <pubDate>Tue, 10 Mar 2026 18:13:40 GMT</pubDate>
            <atom:updated>2026-03-10T18:13:40.906Z</atom:updated>
            <content:encoded><![CDATA[<p>Assume a table:</p><p>Employees</p><p>| id | name | department | salary | manager_id | join_date |</p><p>SQL Interview Practice Questions<br>Basic Queries<br>Q1. Write a query to fetch all employees.</p><p>Q2. Get only name and salary from employees table.</p><p>Q3. Find employees whose salary is greater than 50000.</p><p>Filtering<br>Q4. Find employees who belong to the IT department.</p><p>Q5. Find employees whose salary is between 40000 and 80000.</p><p>Q6. Find employees whose name starts with letter ‘A’.</p><p>Sorting<br>Q7. Get employees sorted by salary in descending order.</p><p>Aggregate Functions<br>Q8. Find the total number of employees.</p><p>Q9. Find the highest salary.</p><p>Q10. Find the average salary.</p><p>GROUP BY<br>Q11. Find total salary paid in each department.</p><p>Q12. Find number of employees in each department.</p><p>HAVING<br>Q13. Find departments having more than 2 employees.</p><p>DISTINCT<br>Q14. Find unique departments from employees table.</p><p>Subquery<br>Q15. Find employees earning more than average salary.</p><p>Second Highest Salary<br>Q16. Find second highest salary from employees table.</p><p>Self Join<br>Q17. Find employee name with their manager name.</p><p>Duplicate Records<br>Q18. Find duplicate employee names.</p><p>Delete Duplicate Records<br>Q19. Write query to delete duplicate employees but keep one record.</p><p>Date Query<br>Q20. Find employees who joined in the last 30 days.<br> — — — — -Answer — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -<br>1 SELECT * FROM EMPLOYEES<br>2 SELECT NAME, SALARY FROM EMPLOYEES<br>3 SLECT * FROM EMPLOYEES WHERE SALARY&gt;50000<br>4 SELECT * FROM EMPLOYEES WHERE DEPARTMENT=’IT’<br>5 SELECT * FROM EMPLOYEES WHERE SALARY BETWEEN 40000 AND 80000<br>6 SELECT * FROM EMPLOYEES WHERE NAME LIKE ‘A%’<br>7 SELECT * FROM EMPLOYEES ORDER BY SALARY DESC<br>8 SELECT COUNT(*) FROM EMPLOYEES<br>9 SELECT MAX(SALARY) FROM EMPLOYEES<br>10 SELECT AVG(SALARY) FROM EMPLOYEES<br>11 SELECT DEPARTMENT,SUM(SALARY) FROM EMPLOYEES GROUP BY DEPARTMENT <br>12 SELECT DEPARTMENT,COUNT(*) FROM EMPLOYEES GROUP BY DEPARTMENT <br>13 SELECT DEPARTMENT, COUNT(*) FROM EMPLOYEES GROUP BY DEPARTMENT HAVING COUNT(*)&gt;2 <br>14 SELECT DISTINCT DEPARTMENT FROM EMPLOYEES <br>15 SELECT * FROM EMPLOYEES WHERE SALARY &gt; (SELECT AVG(SALARY) FROM EMPLOYEES)<br>16 SELECT MAX(SALARY) FROM EMPLOYEES WHERE SALARY &lt; (SELECT MAX(SALARY) FROM EMPLOYEES)<br>17 SELECT E.NAME AS EMPLOYEES , M.MAN_NAME AS MANAGER FROM EMPLOYEES E LEFT JOIN Manager M ON E.MANAGERID=M.ID <br>18 SELECT NAME, COUNT(*) FROM EMPLOYEES GROUP BY NAME HAVING COUNT(*)&gt;1 X<br>19 DELETE FROM EMPLOYEES WHERE ID NOT IN (SELECT MIN(ID) FROM EMPPLOYEES GROUP BY NAME ) X<br>20 SELECT * FROM EMPLOYEES WHERE JOIN_DATE &gt; CURRENT DATE — INTERVAL 30 DAY</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f88df224ca6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL In short notes]]></title>
            <link>https://medium.com/@nidhii200107/sql-in-short-notes-ee3c80f590ea?source=rss-0aad5dc097df------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee3c80f590ea</guid>
            <category><![CDATA[revise-sql]]></category>
            <dc:creator><![CDATA[Nidhi Pal]]></dc:creator>
            <pubDate>Tue, 10 Mar 2026 05:49:20 GMT</pubDate>
            <atom:updated>2026-03-10T05:49:20.864Z</atom:updated>
            <content:encoded><![CDATA[<p>SQL In short notes</p><p>1.Difference between WHERE vs HAVING<br>WHERE filters individual rows before GROUP BY(no aggregates);<br>HAVING filters grouped results after GROUP BY(support aggregates like SUM)<br>2.INNER JOIN VS LEFT JOIN<br>INNER return matching rows from both tables; LEFT returns all rows from left table plus right table rows(NULLS for non-matches)<br>3.DELETE vs TRUNCATE vs DROP<br>DELETE removes rows selectively(loggable, rollbackable);<br>TRUNCATE removes all rows quickly(resets identity, minimally logged);<br>DROP deletes entire table structure.<br>4.Clustered vs Non-Clustered Index<br>Clustered sorts/reorders table data physically by index key(1 per table)<br>Non-Clustered creates separate lookup structure(multiple allowed)<br>5.Primary Key vs Unique Key <br>PRIMARY key enforces uniqueness + non-null(1 per table, clustered by default)<br>UNIQUE key enforces uniqueness(allows nulls, multiple allowed).<br>6.Normalization<br>Process to eliminate data redundancy via normal forms (1NF:atomic values,2NF:no partial dependencies;3NF: no transitive dependencies)<br>7.ACID Properties:<br>Atomicity (all or nothing)<br>Consistency (valid state)<br>Isolation (concurrent safety)<br>Durability (committed permanence)<br>8.TRANSACTIONS<br>Unit of work ensuring ACID compliance, begins with BEGIN, commits with COMMIT, roll back on error.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -</p><p>Some Examples for this:<br>1 Find employees who joined in last 30 days<br>SELECT * FROM EMPLOYEES WHERE JOINING_DATE&gt;CURRENT_DATE — INTERVAL 30 DAY<br>2 Get department with highest salary sum<br>SELECT DEPARTMENT FROM EMPLOYEES GROUP BY DEPARTMENT ORDER BY SUM(SALARY) DESC LIMIT 1<br>3 Find employees who don’t belong to any department<br>SELECT * FROM EMPLOYEES WHERE DEPT_ID IS NULL</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee3c80f590ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Asynchronous Programming and Performance Optimization in C# Applications]]></title>
            <link>https://medium.com/@nidhii200107/advanced-asynchronous-programming-and-performance-optimization-in-c-applications-7a10c7b4d502?source=rss-0aad5dc097df------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a10c7b4d502</guid>
            <dc:creator><![CDATA[Nidhi Pal]]></dc:creator>
            <pubDate>Wed, 15 Oct 2025 09:34:06 GMT</pubDate>
            <atom:updated>2025-10-15T09:34:06.453Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>As enterprise applications increase in scale and complexity, traditional synchronous programming models frequently become bottlenecks, limiting responsiveness and scalability. Since the introduction of .NET Framework 4.5, C# has evolved significantly, offering a rich suite of asynchronous programming constructs that empower developers to build highly efficient and scalable applications. Mastery of these advanced asynchronous patterns, combined with strategic performance optimization techniques, is crucial to mitigating common challenges such as resource contention and application bottlenecks, thereby unlocking the full performance potential of modern C# solutions.</p><h3>Foundations of Asynchronous Programming in C#</h3><p>Asynchronous programming in C# revolves around the async and await keywords, which implement the Task-based Asynchronous Pattern (TAP). These constructs enable non-blocking execution paths, improving application responsiveness and throughput. However, to realize their full benefits, developers must carefully navigate potential pitfalls including deadlocks, excessive context switching, and thread pool exhaustion.</p><h3>Key Patterns</h3><ul><li>Async and Await: Simplify writing readable and maintainable asynchronous code.</li><li>Task Parallel Library (TPL): Provides granular control over the execution and synchronization of concurrent tasks.</li></ul><h3>Advanced Techniques for Asynchronous Programming</h3><h3>Custom Task Scheduling</h3><p>Creating custom task schedulers allows fine-tuning of task execution rules, optimizing CPU utilization and enhancing throughput in high-demand environments.</p><h3>ValueTask for Reduced Allocations</h3><p>Employing ValueTask over Task in scenarios where operations frequently complete synchronously reduces heap allocations, lowering garbage collection impact and improving performance.</p><h3>Asynchronous Streams</h3><p>The IAsyncEnumerable&lt;T&gt; interface facilitates efficient asynchronous data streaming, optimizing memory consumption and resource management for data-intensive applications.</p><h3>Parallel Execution and Concurrency Management</h3><ul><li>Data Partitioning: Dividing workloads across multiple tasks to maximize parallel processing efficiency.</li><li>Concurrency Controls: Using constructs such as SemaphoreSlim and channels to regulate concurrent execution and prevent resource contention.</li></ul><h3>Performance Optimization Strategies</h3><h3>Minimizing Synchronization Overhead</h3><p>Reducing reliance on locks by leveraging lock-free algorithms, Interlocked operations, and thread-safe collections improves concurrency and throughput.</p><h3>Efficient Asynchronous I/O</h3><p>Utilizing asynchronous I/O operations (e.g., Stream.ReadAsync) avoids thread blocking, enabling scalable handling of I/O-bound workloads.</p><h3>Avoiding Unnecessary Context Captures</h3><p>Incorporating ConfigureAwait(false) strategically prevents unnecessary synchronization context captures, reducing context switch overhead—especially crucial in library and server-side code.</p><h3>Profiling and Benchmarking</h3><p>Employing profiling tools such as Visual Studio Profiler, dotTrace, and benchmarking frameworks like BenchmarkDotNet is vital for diagnosing performance bottlenecks and validating optimizations.</p><h3>Challenges and Best Practices</h3><ul><li>Avoiding Deadlocks: Careful management of synchronization contexts and async call patterns is paramount.</li><li>Exception Handling: Robust propagation and handling of exceptions within asynchronous workflows ensures application stability.</li><li>Resource Management: Implementing IAsyncDisposableand invoking DisposeAsync appropriately to clean up unmanaged resources.</li></ul><h3>Conclusion</h3><p>Advanced asynchronous programming in C# offers a powerful paradigm for developing highly performant and scalable applications. A strong grasp of asynchronous patterns, task scheduling, resource management, and concurrency control is essential. Continuous profiling and embracing evolving language features such as asynchronous streams position developers to meet the rigorous performance demands of modern enterprise systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a10c7b4d502" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>