How I replaced if statements with a Dictionary delegate in C#
Let's say you need to implement a feature that returns a different package based on the user-provided coupon code. So you start with a model: public record Package { public int Id { get ; set ; } public string Name { get ; set ; } public double Price { get ; set ; } } And you write a function that returns a different package based on the coupon code: private static Package GetPackageFromCoupon ( string coupon ) { if ( coupon == "ABC" ) { return new Package { Id = 1 , Name = "PS5 Controller" , Price = 50.00 }; } if ( coupon == "EBC" ) { return new Package { Id = 2 , Name = "Iphone X" , Price = 200.00 }; } if ( coupon == "DDD" ) { return new Package { Id = 3 , Name = "X7 Mouse" , Price = 20.00 }; } return new Package { Id = 1000 , Name = "Soda" , Price = 1.00 }; } And invoke it from your main method: internal class Program { static void Main ( string [] args ) { var package = GetPackageFromCoupon ( "ABC" ); Console . WriteLine ( package ); Console . ReadLine (); } } Quick test Provide expected parameters and inspect the results. "ABC" => Package { Id = 1 , Name = PS5 Controller , Price = 50 } "EBC" => Package { Id = 2 , Name = Iphone X , Price = 200 } "DDD" => Package { Id = 3 , Name = X7 Mouse , Price = 20 } Works as expected. Also, if you enter something that doesn't exist: "a" => Package { Id = 1000 , Name = Soda , Price = 1 } The Problem What if you need to add more coupon codes and return different variations of the Package object? Well, it's gonna get pretty messy very soon. Quick solution - Dictionary Rather than writing every possible variation in the if block, create a dictionary where the key is the coupon code and the value is the Package: private static readonly Dictionary < string , Package > _packages = new () { [ "ABC" ] = new Package { Id = 1 , Name = "PS5 Controller" , Price = 50.00 }, [ "EBC" ] = new Package { Id = 2 , Name = "Iphone X" , Price = 200.00 }, [ "DDD" ] = new Package { Id = 3 , Name = "X7 Mouse" , Price = 20.00 }, }; The next step is to