C# tutorial : Delegates in C#

2
  Uncategorized
C# Delegate

C# Delegate

C# tutorial : Delegates in C# are references types to encapsulate named or anonymous methods. Delegates are type safe and secure, you can pass them as parameter to methods. Delegates must be instantiated with methods that have same signature.

How to declare a delegate in C#?

public delegate void Display (string name);

public static void DisplayName(string name)

{

// Write your code here

}

How to instantiate delegate?

// Passing method name as parameter

Display displayDelegate = new Display(DisplayName);

// Or simple way

Display displayDelegate  = DisplayName;

// Anonymous method way

Display displayDelegate  = delegate(string name) {  // Your code here };

// Lambda expression

Display displayDelegate  = name => {// Your code here };

Delegate in C# allow:

  • Methods to be passed as parameters
  • To define callback methods
  • Delegates can be chained together to call many methods
  • Methods signature do not need to match exactly (covariance, contravariance)
  • Delegates are basis for events
  • All types of anonymous methods, lambda expression are compiled into delegates
  • Delegates can point to static methods
  • Delegates are immutable; once created, the invocation list of a delegate does not change.

Where to use delegates ?

  • LINQ
  • Event Handlers
  • Starting threads
  • Callbacks or asynch API
  • When you want to apply some template code with special logic, where delegate will provide the logic
  • Writing on the fly code e.g. Anonymous methods
  • To delay execution of functions
  • To call many methods with single call
  • covariance allows you to build a single delegate that can point to methods returning class types related by classical inheritance
  • contra variance allows you to build a single delegate that can point to methods taking class types related by classical inheritance
  • Delegates provide polymorphism

Where to not use delegates?

  • To call private methods in same class

2 thoughts on “C# tutorial : Delegates in C#

  1. Hi! I could have sworn I’ve been to this blog before but after browsing through some of the post I realized it’s new to me. Anyways, I’m definitely glad I found it and I’ll be bookmarking and checking back often!

Leave a Reply

Your email address will not be published. Required fields are marked *