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. */

Difference between ref and out parameters


Ref and out parameters are used to pass an argument within a method. In this article, you will learn the differences between these two parameters.

Ref

The ref keyword is used to pass an argument as a reference. This means that when value of that parameter is changed in the method, it gets reflected in the calling method. An argument that is passed using a ref keyword must be initialized in the calling method before it is passed to the called method.

Out

The out keyword is also used to pass an argument like ref keyword, but the argument can be passed without assigning any value to it. An argument that is passed using an out keyword must be initialized in the called method before it returns back to calling method.

Program with ref and out keyword

  1. public class Example
  2. {
  3. public static void Main() //calling method
  4. {
  5. int val1 = 0; //must be initialized
  6. int val2; //optional
  7.  
  8. Example1(ref val1);
  9. Console.WriteLine(val1); // val1=1
  10.  
  11. Example2(out val2);
  12. Console.WriteLine(val2); // val2=2
  13. }
  14.  
  15. static void Example1(ref int value) //called method
  16. {
  17. value = 1;
  18. }
  19. static void Example2(out int value) //called method
  20. {
  21. value = 2; //must be initialized
  22. }
  23. }
  24.  
  25. /* Output
  26. 1
  27. 2
  28. */

Note

  1. Do not be confused with the concept of passing by reference and the concept of reference type. These two concepts are not the same.
  2. A value type or a reference type can be passed to method parameter by using ref keyword. There is no boxing of a value type when it is passed by reference.
  3. Properties cannot be passed to ref or out parameters since internally they are functions and not members/variables.

Ref and out in method overloading

Both ref and out cannot be used in method overloading simultaneously. However, ref and out are treated differently at run-time but they are treated same at compile time (CLR doesn't differentiates between the two while it created IL for ref and out). Hence methods cannot be overloaded when one method takes a ref parameter and other method takes an out parameter. The following two methods are identical in terms of compilation.
  1. class MyClass
  2. {
  3. public void Method(out int a) // compiler error “cannot define overloaded”
  4. {
  5. // method that differ only on ref and out"
  6. }
  7. public void Method(ref int a)
  8. {
  9. // method that differ only on ref and out"
  10. }
  11. }
However, method overloading can be done, if one method takes a ref or out argument and the other method takes simple argument. The following example is perfectly valid to be overloaded.
  1. class MyClass
  2. {
  3. public void Method(int a)
  4. {
  5.  
  6. }
  7. public void Method(out int a)
  8. {
  9. // method differ in signature.
  10. }
  11. }

C# Environment

Integrated Development Environment (IDE) for C#

Microsoft provides the following development tools for C# programming:
  • 1- Visual Studio 2016 (VS)
  • 2- Visual C# 2016 Express (VCE)
  • 3- Visual Web Developer
The last two are free and available from Microsoft official website. Using these tools, you can write all kinds of C# programs from simple to more complex applications.
Visual C# Express and Visual Web Developer Express edition are trimmed down versions of Visual Studio and has the same appearance. They retain most features of Visual Studio.

The .Net Framework

Using this platform  helps you to write the following types of applications:
  • 1- Windows applications
  • 2- Web applications
  • 3- Web services
The framework has been designed in such a way that it can be used from any of the following languages: C#, C++, Visual Basic, Jscript, COBOL, etc. All these languages can access the framework as well as communicate with each other.
This Framework contains library of codes used by the client languages such as C#. These are some of the components of .Net framework:
  • 1- Common Language Runtime (CLR)
  • 2- The .Net Framework Class Library
  • 3- Metadata and Assemblies
  • 4- Windows Forms
  • 5- ASP.Net and ASP.Net AJAX
  • 6- ADO.Net

C# Overview


C# is a modern object-oriented programming language developed by Microsoft and approved by European Computer Manufacturers Association (ECMA) and International Standards Organization (ISO).
C# was developed by Anders Hejlsberg and his team during the development of .Net Framework.
C# is used as a professional programming  language for many reasons
  1. Object Oriented
  2. Easy to learn
  3. Produces efficient programs
  4. Part of .Net Framework

C# Programming Features :

  1. Standard library
  2. Automatic garbage collector
  3. Easy to use generics
  4. Delegates and events managements

C# Versions

C# has evolved much since its first release in 2002. C# was introduced with .NET Framework 1.0 and the current version of C# is 6.0
The following table lists important features introduced in each version of C#:
VersionFeatures
C# 1.0
  • Basic features
C# 2.0
  • Generics
  • Partial types
  • Anonymous methods
  • Iterators
  • Nullable types
  • Private setters (properties)
  • Method group conversions (delegates)
  • Covariance and Contra-variance
  • Static classes
C# 3.0
  • Implicitly typed local variables
  • Object and collection initializers
  • Auto-Implemented properties
  • Anonymous types
  • Extension methods
  • Query expressions
  • Lambda expressions
  • Expression trees
  • Partial Methods
C# 4.0
  • Dynamic binding (late binding)
  • Named and optional arguments
  • Generic co- and contravariance
  • Embedded interop types
C# 5.0
  • Async features
  • Caller information