Posts

Showing posts from April 15, 2025

Mastering Tuples and Deconstruction in C#

Mastering Tuples and Deconstruction in C# In C#, when you want to return more than one value from a method or unpack multiple values into variables elegantly,  tuples  and  deconstruction  come to the rescue.   What is a Tuple? A  Tuple  is a data structure that groups multiple values into a single object. var oldTuple = Tuple.Create("John", 25); Console.WriteLine(oldTuple.Item1); // John Console.WriteLine(oldTuple.Item2); // 25 But the Item1, Item2 naming isn’t very readable. That’s why C# 7.0 introduced  ValueTuple  with better syntax: var newTuple = ("John", 25); Console.WriteLine(newTuple.Item1); // John Even better, you can name the fields: var person = (Name: "John", Age: 25); Console.WriteLine(person.Name); // John   Deconstruction: Unpack with Style Tuples can be  deconstructed  into separate variables. (string name, int age) = ("Alice", 30); Console.WriteLine(name); // Alice Consol...

Understanding Delegates in .NET Core: Types, Scenarios, Pros & Cons

Understanding Delegates in .NET Core: Types, Scenarios, Pros & Cons Delegates are one of the core building blocks of the .NET platform, enabling flexibility and extensibility in a clean and type-safe manner. In this blog, we’ll break down what delegates are, their types, practical scenarios where you can use them, and the pros and cons of using them in .NET Core applications.   What is a Delegate? A  delegate  in .NET is a type that encapsulates a reference to a method. Delegates are similar to function pointers in C or C++, but are type-safe and secure. They are mainly used to define callback methods and implement event handling. Example: public delegate int Calculate(int x, int y);   public class MathOperations {     public int Add(int a, int b) => a + b;     public int Subtract(int a, int b) => a - b; }   // Usage MathOperations math = new MathOperations(); Calculate calc = new Ca...