Skip to main content

Understanding Delegates in C#

A delegate is a reference type that holds the reference of a class method. Any method which has the same signature as delegate can be assigned to delegate. It is very similar to the function pointer but with a difference that delegates are a type-safe. We can say that it is the object-oriented implementation of function pointers.
There are three steps for defining and using delegates:
  1. Declaration

    A delegate is declared by using the keyword delegate, otherwise it resembles a method declaration.
  2. Instantiation

    To create a delegate instance, we need to assign a method (which has same signature as delegate) to delegate.
  3. Invocation

    Invoking a delegate is like as invoking a regular method.
  1. //1. Declaration
  2. public delegate int MyDelagate(int a, int b); //delegates having same signature as method
  3.  
  4. public class Example
  5. {
  6. // methods to be assigned and called by delegate
  7. public int Sum(int a, int b)
  8. {
  9. return a + b;
  10. }
  11.  
  12. public int Difference(int a, int b)
  13. {
  14. return a - b;
  15. }
  16. }
  17. class Program
  18. {
  19. static void Main()
  20. {
  21. Example obj = new Example();
  22. // 2. Instantiation : As a single cast delegate
  23. MyDelagate sum = new MyDelagate(obj.Sum);
  24. MyDelagate diff = new MyDelagate(obj.Difference);
  25. // 3.Invocation
  26. Console.WriteLine("Sum of two integer is = " + sum(10, 20));
  27. Console.WriteLine("Difference of two integer is = " + diff(20, 10));
  28. }
  29. }
  30.  
  31. /* Out Put
  32.  
  33. Sum of two integer is = 30
  34. Difference of two integer is = 10
  35. */

Key points about delegates

  1. Delegates are like C++ function pointers but are type safe.
  2. Delegates allow methods to be passed as parameters.
  3. Delegates are used in event handling for defining callback methods.
  4. Delegates can be chained together i.e. these allow defining a set of methods that executed as a single unit.
  5. Once a delegate is created, the method it is associated will never changes because delegates are immutable in nature.
  6. Delegates provide a way to execute methods at run-time.
  7. All delegates are implicitly derived from System.MulticastDelegate, class which is inheriting from System.Delegate class.
  8. Delegate types are incompatible with each other, even if their signatures are the same. These are considered equal if they have the reference of same method.

Types of delegates

  1. Single cast delegate

    A single cast delegate holds the reference of only single method. In previous example, created delegate is a single cast delegate.
  2. Multi cast delegate

    A delegate which holds the reference of more than one method is called multi-cast delegate. A multicast delegate only contains the reference of methods which return type is void. The + and += operators are used to combine delegate instances. Multicast delegates are considered equal if they reference the same methods in the same order.
  1. //1. Declaration
  2. public delegate void MyDelagate(int a, int b);
  3. public class Example
  4. {
  5. // methods to be assigned and called by delegate
  6. public void Sum(int a, int b)
  7. {
  8. Console.WriteLine("Sum of integers is = " + (a + b));
  9. }
  10.  
  11. public void Difference(int a, int b)
  12. {
  13. Console.WriteLine("Difference of integer is = " + (a - b));
  14. }
  15. }
  16. class Program
  17. {
  18. static void Main()
  19. {
  20. Example obj = new Example();
  21. // 2. Instantiation
  22. MyDelagate multicastdel = new MyDelagate(obj.Sum);
  23. multicastdel += new MyDelagate(obj.Difference);
  24. // 3. Invocation
  25. multicastdel (50, 20);
  26. }
  27. }
  28.  
  29. /* Out put
  30.  
  31. Sum of integers is = 70
  32. Difference of integer is = 30
  33.  
  34. */

Comments

Popular posts from this blog

gcAllowVeryLargeObjects Element

There are numerous new features coming with .NET 4.5 and here, on this blog, you can find several posts about it. But the feature we are goint to talk about today is very exciting, because we were waiting for it more than 10 years. Since .NET 1.0 the memory limit of .NET object is 2GB. This means you cannot for example create array which contains elements with more than 2GB in total. If try to create such array, you will get the OutOfMemoryException. Let’s see an example how to produce OutOfMemoryException. Before that Open Visual Studio 2012, and create C# Console Application, like picture below. First lets create simple struct with two double members like example below: 1 2 3 4 5 6 7 8 9 10 11 12 public struct ComplexNumber {      public double Re;      public double Im;      public ComplexNumber( double re, double im)      {    ...

Support for debugging lambda expressions with Visual Studio 2015

Anyone who uses LINQ (or lambdas in general) and the debugger will quickly discover the dreaded message “Expression cannot contain lambda expressions”. Lack of lambda support has been a limitation of the Visual Studio Debugger ever since Lambdas were added to C# and Visual Basic.  With visual studio 2015 Microsoft has added support for debugging lambda expressions. Let’s first look at an example, and then I’ll walk you through current limitations. Example To try this yourself, create a new C# Console app with this code: using System.Diagnostics; using System.Linq; class Program { static void Main() { float[] values = Enumerable.Range(0, 100).Select(i => (float)i / 10).ToArray(); Debugger.Break(); } } Then compile, start debugging, and add “values.Where(v => (int)v == 3).ToArray()” in the Watch window. You’ll be happy to see the same as what the screenshot above shows you. I am using Visual Studio 2015 Preview and it has some limitati...

How to allow a very large object in .net application?

Since .NET 1.0 the memory limit of .NET object is 2GB. This means you cannot for example create array which contains elements with more than 2GB in total. If try to create such array, you will get the OutOfMemoryException. Let’s see an example how to produce OutOfMemoryException. Before that Open Visual Studio, and create C# Console Application. Lets create simple struct with two double members like example below: public struct ComplexNumber { public double Re; public double Im; public ComplexNumber(double re, double im) { Re = re; Im = im; } } As we know this structure consumes about 16 bytes of memory. So if we want to create array of this type which consume more than 2GB we need to create array at least with 134217728 instances. So this sample program below creates 130000000 (about 1,97 GB) of array. int maxCount = 130000000; ComplexNumber[] arr = null; try { arr = new ComplexNumber[maxCount]; } catch (Exception ex) { Console.WriteLine(ex.Message); } So if we run t...