User Name:


User Email:




This information will only be saved for the purposes of communicating with those who have provided this information voluntarily regarding our services.We will never sell your name or email address to anyone.
© 2018 - First Crazy Developer (Abhishek Kumar)
  

crazydeveloper Delegates in C# .Net

Hi, today we will discuss the most important feature of C# that is "Delegates". When we are coding with C#, it gives us some extra advantage to implement our business requirements. "Delegates" is the one of them, which gives you extra advantage in C#. Here we have the important question: What is delegates in C#?

Delegates used to encapsulate and pass methods as parameters to other methods.  And if we compare with other programming language we can explain like- "Delegates is a function pointer in C# which help us to invoke method at runtime without knowing at compile time."

Above paragraph is a popular definition of Delegates used by developers. Now we move ahead and understand delegates in easy language. In C# we have a data type that allows us to pass methods as parameters of other methods. This data type is called a delegates.

Now the next question we have - "What are the advantage of Delegate in C# and why Delegates?"

The answer of above first question is "Delegates are reference type, object-oriented, type-safe and secure." Move ahead and start discussion about second question - Why Delegates?

 

Look at the following points and get the answer of above question:

It used to reference (call/invoke)  multiple method on a single event.

It is best to use in callback (asynchronous) methods.

We can decide to call/invoke method at runtime with delegates.

Used with LINQ for parsing the ExpressionTree.

Decoupling and implement generic behaviours with delegates.

Best to use implement events and the call-back methods

 

If anybody have more scenario then suggest us.....

 

After above all the above discussion we can say "Delegates hold the reference of method and invoke at runtime without care about the class of the object that it references. The only this which matters is that the method's arguments type and return type match the delegate's.

 

Now move ahead and understand the types of Delegates in C#:

1.) Single Delegate   

2.) Multicast Delegate   

3.) Generic Delegate

 

We have to follow some steps when we implement the Delegates in our code:

a.)   Declaration

b.)   Instantiation

c.)   Invocation

 

Now we have the good understand the concept of Delegates. So move ahead and implement the above concept in our code. We start declaration of delegates.

 

Look at the following syntax:

access identifier -- delegate -- return type -- delegate name -- ( [parameters])

 

In the above syntax we can see the declaration way of delegate. First we define the access identifier then use delegate keyword after that define the return types of delegate then declare the delegates name and then after define the parameters. 

 

Look at the following code:

  1. public delegate void Calculation()

In the above code we can see there is a delegate named “Calculation" and return type is void with no parameters. Above delegates can encapsulate any method that takes no parameters and returns no value.

 

Look at the following code:

  1. public delegate int delegateMathActivity (int num1,int num2 )

In the above code we can see there is a delegate named "delegateMathActivity" and return type is integer with two integer type parameters. And above delegates can encapsulate any method that takes two integer as parameters and returns an integer.

After the discussion of declaration of delegates now move ahead and start instantiation of delegates:

 

Look at the following code:

  1. public int sampleMethod(int num1, int num2)
  2. {
  3.     return num1+num2;
  4. }
  5. delegateMathActivity simpleDelegate = new delegateMathActivity(sampleMethod);

In the above code we can see there is a delegateMathActivity type delegate named "simpleDelegate" and in constructor we pass the method name which will invoke with same signature of delegates. We have also function named "sampleMethod" which used with delegates.

After finish the instantiation of delegates now start Invocation of delegates:

 

Look at the following code:

  1. simpleDelegate();

In the above code we can see here we just called the object of delegates and this line of code will invoke the sampleMethod function.

After all the above discussion start coding and one by one we understand the different types of delegates with example. Now first we start with Single delegates types.

Single Delegates:

Look at the following code:

  1. public class DelegateSample
  2. {
  3. public delegate void mySampleDelegate();
  4. public static void sampleMethod()
  5. {
  6. //Sample code
  7. }
  8. public static void Main()
  9. {
  10. // Instantiation
  11. mySampleDelegate simpleDelegate = new mySampleDelegate(sampleMethod);
  12. // Invocation
  13. simpleDelegate();
  14. }
  15. }

In the above code we can see it's easy to understand - "how we can use delegates in our code?”, now we will try to use delegate with instance & static method.

Look at the following code:

  1. namespace MyDelegateSampleData
  2. {
  3. public delegate void mySampleDelegate();
  4. public class DelegateSample
  5. {
  6. public void sampleInstanceMethod()
  7. {
  8. Console.WriteLine("Called instance method.");
  9. }
  10. static public void sampleStaticMethod ()
  11. {
  12. Console.WriteLine("Called static method.");
  13. }
  14. }
  15. public class MainBaseClass
  16. {
  17. static public void Main()
  18. {
  19. DelegateSample obj = new DelegateSample();
  20. // Map the delegate to the instance method:
  21. mySampleDelegate objDelegate = new mySampleDelegate(obj.sampleInstanceMethod);
  22. objDelegate();
  23. // Map to the static method:
  24. objDelegate = new mySampleDelegate(DelegateSample.sampleStaticMethod);
  25. objDelegate();
  26. }
  27. }
  28. }

In the above code we understood the Single Delegates now move ahead and start discussion with Multicasting of Delegates. Here we have an important question -"What is the use of Multicast Delegates in C#?"

Multicasting is the way, which help us to add multiple delegates with single point reference. We can't only add but also remove the delegates. How can we do that? We have two operators which give us power to do that. "+" used to add & "-" used to remove delegates.

 

Look at the following code:

  1. public class DelegateSample
  2. {
  3. // Declaration
  4. public delegate void mySampleDelegate(int num1,int num2);
  5. static int number = 7;
  6. public static void Sum (int num1, int num2)
  7. {
  8. number= number + num1 + num2;
  9. }
  10. public static void Multiply(int num1, int num2)
  11. {
  12. number= number + (num1 * num2);
  13. }
  14. public static void Main()
  15. {
  16. mySampleDelegate obj = new mySampleDelegate(Sum);
  17. obj += new mySampleDelegate(Multiply);
  18. obj(10, 5);
  19. }
  20. }

In the above code we can see there is a delegates named "mySampleDelegate" with return type is void and two integer type parameters. We have also two method named "Sum & Multiply" with same signature as delegates. In the main method first we declared an object of delegates "mySampleDelegate" and pass "Sum" method in constructor. Now in the next line we used the multicasting "obj += new mySampleDelegate(Multiply);". Here we add one more method named "Multiply" with delegates. After this line when we invoked the delegates above two method called with single invoke. This is magic of delegates in C#. We can also remove the reference of multiple method from delegates.

Look at the following code:

  1. public static void Main()
  2. {
  3. mySampleDelegate obj = new mySampleDelegate(Sum);
  4. //add method
  5. obj += new mySampleDelegate(Multiply);
  6. //invoke
  7. obj(10, 5);
  8. //remove method
  9. obj -= new mySampleDelegate(Multiply);
  10. //invoke
  11. obj(10, 5);
  12. }

In the above discussion I hope we understood the basic concept of delegates now move ahead and start discussion with some complex scenario like delegate with runtime invoke.

Look at the following code:

  1. class Program
  2. {
  3. // Declaration
  4. public delegate int mySampleDelegate(int num1, int num2);
  5. public static int Sum(int num1, int num2)
  6. {
  7. return num1 + num2;
  8. }
  9. public static int Sub(int num1, int num2)
  10. {
  11. return num1 - num2;
  12. }
  13. public static int Multiply(int num1, int num2)
  14. {
  15. return (num1 * num2);
  16. }
  17. public static int delegateTaskSync(mySampleDelegate obj)
  18. {
  19. // Invocation
  20. return obj(25, 20);
  21. }
  22. public static void Main()
  23. {
  24. int i = 0;// 0-Sum,1-Sub,2-Multiply
  25. try
  26. {
  27. i = Int32.Parse(Console.ReadLine());
  28. int result = 0;
  29. switch (i)
  30. {
  31. case 0:
  32. result = delegateTaskSync(new mySampleDelegate(Sum));
  33. Console.WriteLine("Output value=" + result.ToString());
  34. Console.ReadLine();
  35. break;
  36. case 1:
  37. result = delegateTaskSync(new mySampleDelegate(Sub));
  38. Console.WriteLine ("Output value=" + result.ToString());
  39. Console.ReadLine();
  40. break;
  41. case 2:
  42. result = delegateTaskSync(new mySampleDelegate(Multiply));
  43. Console.WriteLine("Output value=" + result.ToString ());
  44. Console.ReadLine();
  45. break;
  46. default:
  47. Console.WriteLine ("Invalid Input");
  48. Console.ReadLine();
  49. break;
  50. }
  51. }
  52. catch(Exception ex)
  53. {
  54. Console.WriteLine("Invalid Input");
  55. Console.ReadLine();
  56. }
  57. }
  58. }

In above code we can see there are three method named "Sum, Sub and Multiply" and a delegate "mySampleDelegate" with same signature as method. There is one more method "delegateTaskSync" and we are passing delegates as a parameter in this method. If we look back and remember what we discussed in this article - “In C# with the help of delegate we can pass method as parameter." In "delegateTaskSync" method we are doing same logic. In the main method we take input value from user and as per provide value we invoke method at runtime. Here with the help of delegates we pass a method as parameter in other method.

Now move ahead after all of the above discussion we have good understanding of delegates. Next we start  discussion about Generic Delegates. Generic Delegate was introduced in .NET 3.5 that don't require to define the delegate instance in order to invoke the methods. So through generic delegates we elimate the process to use delegate like declaration, Instantiation & invocation.

 

 There are three types of generic delegates:

   1.)  Func<>  

   2.)  Action<>  

   3.)  Predicate<>

 

Now in next some lines we will start discussion of the above types. Here again we have a question - "What is Func<> delegates in C#?"

Func<> is used when we want to point to a method that returns a value. It can point to a method that takes up to 16 Parameters and returns a value. Most important part that the final parameter of Func<> is always the return value of the method. (examle Func< int, int, string>,in  this statement Func<> delegate will take 2 int parameters and returns a string value.)

Look at the following code:

  1. class MathActivity
  2. {
  3. static int num=0;
  4. static string passMessage="";
  5. //Methods that takes parameters and returns a value:
  6. public static int Add(int num1, int num2)
  7. {
  8. return num1 + num2;
  9. }
  10. public static string DisplayAddNumber(int a, int b)
  11. {
  12. string str= "The addition of two number is=";
  13. str = str + (a + b).ToString();
  14. return str;
  15. }
  16. public static int getRandomNumber()
  17. {
  18. Random r = new Random();
  19. return r.Next();
  20. }
  21. }
  22. class UseClass
  23. {
  24. static void Main(string[] args)
  25. {
  26. // Func delegates declaration
  27. Func<int, int,int> objFuncAdd = new Func<int, int, int>(MathActivity.Add);
  28. Func<int, int, string> objFuncAddDisplay = new Func<int, int, string>(MathActivity.DisplayAddNumber);
  29. Func<int> objFuncRandomNumber = new Func<int>(MathActivity.getRandomNumber);
  30. // Delegates invocation
  31. int resultAdd = objFuncAdd(10, 7); //Parameter: type: integer, count:2 , Returns type: integer
  32. string resultAddDisplay = objFuncAddDisplay(7, 7); //Parameter: type: integer, count:2 , Returns type: string
  33. int resultRandomNumbers = objFuncRandomNumber(); //Parameter: 0 , Returns type: int
  34. }
  35. }

In the above code we can see, how can we use Func<> in C#. Now move ahead and understand - "What is Action<>?"

 

Action<> is used when we want to point to a method that doesn't return a value. It can point to a method that takes up to 16 Parameters and doesn't return a value. Most important part that the final parameter of Action<> doesn't return any value from the method. (examle Action< int, int, string>,in  this statement Action<> delegate will take 2 int parameters and 1 string parameter.)

   

Look at the following code:

  1. class SampleMathActivity
  2. {
  3. //Methods that takes parameters but returns nothing:
  4. static int num=0;
  5. static string passMessage="";
  6. public static void CountNumbers(int startPoint, int targetPoint)
  7. {
  8. for (int i = startPoint; i <= targetPoint; i++)
  9. {
  10. num=num+i;
  11. }
  12. }
  13. public static void messagePrint(string myMessage)
  14. {
  15. passMessage =myMessage;
  16. }
  17. }
  18. class CallSampleMathActivity
  19. {
  20. static void Main (string[] args)
  21. {
  22. Action<int, int> objActioncountNum = new Action<int, int>(SampleMathActivity.CountNumbers);
  23. Action<string> objActionmsgPrint = new Action<string>(SampleMathActivity.messagePrint);
  24. // Delegates invocation
  25. objActioncountNum (10, 7); //Parameter: type: integer, count:2 , Returns type: can not use
  26. objActionmsgPrint("FirstCrazyDeveloper"); //Parameter: type: strin, count:2 , Returns type: can not use
  27. }
  28. }

After all these above discussion now move ahead to last point to discussion about Predicate <> - "What is Predicate<>?"  

Predicate is a feature that returns true or false. It is being used with lambda expression (=>). It takes generic type as an argument. It allows a predicate function to be defined and passed as a parameter to another function. It is a special case of a Func, in that it takes only a single parameter and always returns a bool.

 The Predicate type in the C# language stores a method that receives one parameter and returns one value of true or false. So we can say "Predicate" a  delegate that returns a Boolean. It is used a lots in filtering lists but can be used wherever you'd like. We can use Predicate<> to search items in a generic collection and Validate the given value.

We can find this Predicate<> into System namespace.

 

Look at the following code:

  1. namespace System
  2. {
  3. public delegate bool Predicate<in T>(T obj);
  4. }

After the above discussion we will look - How to use Predicate with generic collection?

 

Look at the following code:

  1. var studentsList = studentsList.Where (student=>student.Id == 77).FirstOrDefault();

In the above code we can see here we used code to implement Predicate generic collection. Now move ahead to understand more uses of Predicate<>.

Look at the following code:

  1. class PredicateTest
  2. {
  3. static void Main(string[] args)
  4. {
  5. string date="16/07/1986";
  6. string num="77";
  7. Predicate<string> validateDate = d => IsDate(d);
  8. Predicate<string> validateInteger = d => IsNumber(d);
  9. bool isdate=validateDate(date); // output >> true
  10. bool isNumber=validateInteger(num); // output >> true
  11. isdate=validateDate("abc"); // output >> false
  12. isNumber=validateInteger("abc"); // output >> false
  13. }
  14. private static bool IsDate(string date)
  15. {
  16. DateTime dt;
  17. return DateTime.TryParse (date,out dt);
  18. }
  19. private static bool IsNumber(string number)
  20. {
  21. int tempnumber;
  22. return int.TryParse (number, out tempnumber);
  23. }
  24. }

In the above code we learnt how can we validate the given value with Predicate delegates.

 

Following the difference between Generic Delegates:

 

                        Func         Action            Predicate

Arguments         Yes           Yes               Yes

Returns             Yes            No               Boolean Type Only

 

 I hope after all the above discussion we understood the concepts of delegates.

 

Happy reading!

Abhishek


crazydeveloper Home Page 16 June 2015

Become a Fan