C# Journey - 3. Delegates with a practical demonstration
Embarking on a Profound C# Journey: Exploring the Power of Delegates Through Practical Demonstrations
Introduction to Delegates
In C#, delegates are a powerful feature that allows you to define and use references to methods as first-class objects. A delegate is essentially a type-safe function pointer that can point to one or more methods with a compatible signature. Delegates provide a way to implement callback mechanisms, event handling, and other advanced programming scenarios in a clean and flexible manner.
Enhancing Shopping Cart Logic with Delegates
Imagine a shopping cart where the discount percentage increases as the total purchase amount goes up. Not only do we want to display the final discounted total to the user, but we also want to show the original price before any discounts are applied. So, the question arises: How can we efficiently handle these calculations within a single function and return both the subtotal and the total? The answer lies in the power of delegates.
Delegates are a powerful feature in many programming languages, including C#. They allow us to treat methods as first-class citizens, enabling us to encapsulate and pass around not only functions but also the context in which they should be executed. Let's dive into how we can use delegates to solve our shopping cart challenge.
Example:
namespace Delegates
{
public class ProductModel
{
public string Name { get; set; }
public double Price { get; set; }
}
}
namespace Delegates
{
public class ShoppingCartModel
{
public List<ProductModel> Products { get; set; } = new List<ProductModel>();
public delegate void TotalMention (double total);
public double MakeSubtotal(TotalMention totalMention)
{
double subTotal = 0;
foreach (var item in Products)
{
subTotal = subTotal + item.Price;
}
// you can make subTotal this way also
// double subTotal = Products.Sum(x => x.Price);
totalMention(subTotal); // From here, we are calling function in the main ("Mention")
if (subTotal > 100)
{
return subTotal * 0.80;
}
return subTotal;
}
}
}
namespace Delegates
{
class Program
{
static ShoppingCartModel cart = new ShoppingCartModel();
static void Main(string[] args)
{
InitializeCart();
// Just referencing the function, not calling it
Console.WriteLine($"your subtotal is:{cart.MakeSubtotal(Mention)}");
}
// In this function the return type and argument type needs to be the
// same as in ShoppingCartModel delegate
public static void Mention(double subTotal)
{
Console.WriteLine($"your total is:{subTotal}");
}
public static void InitializeCart()
{
cart.Products.Add(new ProductModel { Name = "Bosch", Price = 200.20 });
cart.Products.Add(new ProductModel { Name = "Dewalt", Price = 300.20 });
cart.Products.Add(new ProductModel { Name = "Makita", Price = 150 });
cart.Products.Add(new ProductModel { Name = "Milwoukee", Price = 400.50 });
}
}
}