Skip to main content

Posts

Showing posts from October, 2021
                                                                                      Delegates in C# You want to pass a function as a Parameter ? How does C# handles a callback function or an event handler ? The answer of all these questions is one i.e. a Delegate. Delegate is a reference type datatype that defines a method prototype. We can define a varibale of delegate just like any other datatype that can refer to any method with the same prototype i,e, signature.  Define a Delegate => Set a Target Method => Invoke  eg: public delegate void MyFirstDelegate(string str); // Declaration Note: declaration can be done outside or even inside the class. static void MethodA(string str) { Console.Writeline(str); } //Setting up Target Method 1) MyFirstDelegate del = new  MyFirstDelegate(MethodA);  2) MyFirstDelegate del= MethodA; 3) MyFirstDelegate del = (string msg) => Console.Writeline(msg); //Invoke  del.Invoke("Hello World!"); del("Hello World");