Delegates in C#


A delegate is a type-safe function pointer that can reference a method that has the same signature as that of a delegate.
In short: Rather than pointing to the actual function, you point to a delegate.

Delegates :


  • Used to define callback methods 
  • Implement event handling
  • Declared using "delegate" keyword. 
  • It allows us to pass methods as parameter. 
Types of Delegates: 
  • Simple/Single Delegate - When delegate takes reference with single method. 
  • Multicast Delegate - When delegates takes reference with multiple methods. You can make use + and\or (-) sign to add and subtract methods respectively. This creates an invocation list and is called upon the order of addition. 
  • Generic Delegate 

Different ways of creating a delegate in C#: 
  • Action - Action takes up to 16 input Parameters and doesn't return a value.
    • Example: delegate int Action(T1 arg1, T2 arg2); 
  • Func
  • Predicate
  • Lambda
  • Anonymous Types.
Fun Facts:
     You can point to multiple methods and these are called multicast delegates. 
     Delegates in C# are similar to C++ function pointer.
     Delegates can be used to point to a static method or an instance method.  

More about delegates and code in the next section.

Comments

Popular posts from this blog

Knowing too much is bad(in the world of OOP)

Reverse a LinkedList Algorithm

DateTime.Now in C#