1. What is a Delegate in C#?
A delegate is a type that defines a method signature, allowing methods to be passed as parameters. Delegates are similar to pointers to functions in C++, but are type-safe and secure.
public delegate void MyDelegate(string message); public class Program { public static void Main(string[] args) { MyDelegate del = new MyDelegate(ShowMessage); del("Hello, World!"); } public static void ShowMessage(string message) { Console.WriteLine(message); } }
2. How do you declare and instantiate a Delegate?
Declare a delegate using the delegate
keyword followed by a method signature. Instantiate it by assigning a method that matches the delegate's signature.
public delegate int Operation(int x, int y); public class Program { public static int Add(int a, int b) => a + b; public static void Main(string[] args) { Operation op = Add; int result = op(5, 3); Console.WriteLine(result); // Output: 8 } }
3. What are Multicast Delegates?
Multicast delegates are delegates that hold references to more than one method. When invoked, they call all the methods they reference in sequence.
public delegate void Notify(); public class Program { public static void Notify1() => Console.WriteLine("Notification 1"); public static void Notify2() => Console.WriteLine("Notification 2"); public static void Main(string[] args) { Notify notify = Notify1; notify += Notify2; notify(); // Output: Notification 1 Notification 2 } }
4. What are Anonymous Methods and how are they used with Delegates?
Anonymous methods provide a way to define inline methods without needing a separate method declaration, useful for short-lived methods.
public delegate void PrintMessage(string message); public class Program { public static void Main(string[] args) { PrintMessage print = delegate (string msg) { Console.WriteLine(msg); }; print("Hello, Anonymous Methods!"); } }
5. What is the difference between Delegates and Events?
Delegates are function pointers that can be directly invoked, whereas events provide a layer of encapsulation and are used to implement the publisher-subscriber pattern.
public delegate void EventHandler(string message); public class EventPublisher { public event EventHandler OnEvent; public void TriggerEvent(string msg) { OnEvent?.Invoke(msg); } } public class Program { public static void Main(string[] args) { EventPublisher publisher = new EventPublisher(); publisher.OnEvent += ShowMessage; publisher.TriggerEvent("Event Triggered!"); } public static void ShowMessage(string message) { Console.WriteLine(message); } }
6. How can you pass Delegates as Parameters?
Delegates can be passed as parameters to methods, allowing for callback methods or dynamically chosen methods to be executed.
public delegate void Logger(string message); public class Program { public static void LogToConsole(string message) { Console.WriteLine(message); } public static void LogMessage(Logger log, string message) { log(message); } public static void Main(string[] args) { LogMessage(LogToConsole, "Logging a message."); } }
7. What are Func and Action Delegates?
Func
and Action
are predefined generic delegates. Func
delegates return a value, while Action
delegates do not return a value.
public class Program { public static void Main(string[] args) { Func<int, int, int> add = (x, y) => x + y; Action<string> print = message => Console.WriteLine(message); int result = add(3, 4); print($"Result: {result}"); // Output: Result: 7 } }
8. Can Delegates be used with LINQ?
Yes, delegates are often used with LINQ queries, particularly with lambda expressions, to provide method references for operations like Select
, Where
, etc.
public class Program { public static void Main(string[] args) { List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; Func<int, bool> isEven = x => x % 2 == 0; var evenNumbers = numbers.Where(isEven).ToList(); evenNumbers.ForEach(n => Console.WriteLine(n)); // Output: 2 4 } }
9. How do you chain Delegates?
Delegates can be chained together using the +
operator. Chaining allows multiple methods to be invoked sequentially.
public delegate void Process(int number); public class Program { public static void Square(int x) => Console.WriteLine(x * x); public static void Double(int x) => Console.WriteLine(x * 2); public static void Main(string[] args) { Process process = Square; process += Double; process(5); // Output: 25 10 } }
10. What is Covariance and Contravariance in Delegates?
Covariance allows a delegate to return a more derived type than specified, and contravariance allows a delegate to accept parameters of a less derived type.
public delegate Base CovariantDelegate(); public delegate void ContravariantDelegate(Derived d); public class Base { } public class Derived : Base { } public class Program { public static Base Method1() => new Base(); public static Derived Method2() => new Derived(); public static void Method3(Base b) { } public static void Method4(Derived d) { } public static void Main(string[] args) { CovariantDelegate covariantDel; covariantDel = Method2; // Covariance ContravariantDelegate contravariantDel; contravariantDel = Method3; // Contravariance } }
Conclusion
Delegates in C# are a powerful feature that allows methods to be treated as first-class citizens. They enable flexible and dynamic method invocation, play a crucial role in events, and enhance code reusability. Understanding delegates is essential for advanced C# programming and implementing design patterns effectively.
Comments
Post a Comment