Delegates in C# and Types and its usage:
In C#, delegates are a type that represents references to methods. They are used to define and work with method signatures dynamically. Here are some types of delegates and related concepts in C#:
Types of Delegates:
Singlecast Delegates:
✅️Singlecast delegates refer to delegates that can hold references to only one method at a time. They are declared using the delegate keyword and can be used for scenarios where a single method needs to be invoked.
delegate void MyDelegate(int x);
SingleCast Delegate useful to perform Calculation logic based on Methods.Here is an simple example
delegate int AddDelegate(int a, int b);
static void SingleCastDelegates()
{ // Define the delegate
AddDelegate addDelegate = (a, b) => a + b;
// Use the delegate to perform addition
int result = addDelegate(5, 10);
Console.WriteLine(result); // Output: 15
}
Multicast Delegates:
✅️Multicast delegates can hold references to multiple methods. When a multicast delegate is invoked, all the methods it holds are called in the order in which they were added.
delegate void MultiDelegate(int x);
MultiDelegate multiDelegate = Method1;
multiDelegate += Method2;
Here is an example with Order Processing with Multicast Delegate in C#.
internal static class MulticastDelegates
{
// Define delegate types for order processing stages
public delegate void OrderProcessingDelegate(Order order);
// Define an Order class
public class Order
{
public int OrderId { get; set; }
public string CustomerName { get; set; }
public decimal TotalAmount { get; set; }
// Other properties relevant to the order
public Order(int orderId, string customerName, decimal totalAmount)
{
OrderId = orderId;
CustomerName = customerName;
TotalAmount = totalAmount;
}
}
// Order Processor class responsible for processing orders
public class OrderProcessor
{
// Multicast delegate instances for different processing stages
private OrderProcessingDelegate PreProcessOrder;
private OrderProcessingDelegate ProcessOrder;
private OrderProcessingDelegate PostProcessOrder;
// Constructor to initialize delegate instances
public OrderProcessor()
{
PreProcessOrder += ValidateOrder;
ProcessOrder += CalculateTotalAmount;
PostProcessOrder += SendOrderConfirmation;
}
// Method to trigger order processing
public void Process(Order order)
{
PreProcessOrder?.Invoke(order);
ProcessOrder?.Invoke(order);
PostProcessOrder?.Invoke(order);
}
// Example methods for different stages of order processing
private void ValidateOrder(Order order)
{
Console.WriteLine($"Validating order {order.OrderId} for customer {order.CustomerName}");
// Validation logic goes here
}
private void CalculateTotalAmount(Order order)
{
Console.WriteLine($"Calculating total amount for order {order.OrderId}");
// Calculation logic goes here
}
private void SendOrderConfirmation(Order order)
{
Console.WriteLine($"Sending order confirmation for order {order.OrderId} to customer {order.CustomerName}");
// Confirmation sending logic goes here
}
}
static class RunProgram
{
public static void MainsMultiCaste(string[] args)
{
// Create an order
Order order = new Order(1001, "John Doe", 150.50m);
// Create an order processor
OrderProcessor orderProcessor = new OrderProcessor();
// Process the order
orderProcessor.Process(order);
}
}
public static void DelegateRunProgram()
{
RunProgram.MainsMultiCaste(null);
}
}
=====================================================================================================
order Processsing Delegate
==================================================================================================🔸Order class represents an order with relevant properties like OrderId, CustomerName, and TotalAmount.
🔸OrderProcessor class is responsible for processing orders. It has three multicast delegate instances PreProcessOrder, ProcessOrder, and PostProcessOrder, each corresponding to different stages of order processing.
🔸Constructor of OrderProcessor initializes delegate instances with methods representing different processing stages (ValidateOrder, CalculateTotalAmount, and SendOrderConfirmation).
🔸Process method in OrderProcessor triggers order processing by invoking multicast delegates in sequence.
🔸Each processing stage is represented by a method in the OrderProcessor class (ValidateOrder, CalculateTotalAmount, and SendOrderConfirmation). These methods perform specific tasks related to their processing stage.
🌟Using multicast delegates in this manner allows for modular and extensible order processing logic. New processing stages can be added easily by adding corresponding methods and attaching them to the relevant delegate instances.
v>Generic delegates are particularly useful in scenarios where you want to define a delegate that can work with different types, providing flexibility and reusability.
🔸Collections: When working with collections, you might want to perform operations like filtering, mapping, or reducing elements. Using generic delegates allows you to define flexible and reusable functions that can operate on different types of collections.
🔸Event Handling: Generic delegates can be used to define event handlers that can handle events with different types of arguments. This is especially useful in scenarios where you have multiple events with different argument types but want to use a single handler for all events.
🔸Callback Functions: When working with asynchronous operations, you might use callback functions to handle the result of the operation. Using generic delegates allows you to define callback functions that can handle different types of results.
Functional Programming: In functional programming, delegates can be used to represent functions as first-class citizens. Generic delegates enhance this capability by allowing you to define functions that can work with different types.
Comments
Post a Comment