2

base on msdn pages, when we declare a delegate we do need to specify return value and also argument of the method that would be called via delegate.

my question:

let's say I have a method as:

public int MethodA(bool bValue) and also void MethodB(int iValue)

Do I need to declare two different delegates here for each method or I can do it using one?

Thanks.

3 Answers 3

2

Do I need to declare two different delegates here for each method or I can do it using one?

Since these methods have completely different signatures, you need different delegates. However, you can use the built-in Func<bool, int> and Action<int> delegates instead of declaring your own delegate types.

For example, you could use:

Func<bool,int> delegateA = this.MethodA;

Action<int> delegateB = this.MethodB;
// or:  Action<int> delegateB = new Action<int>(this.MethodB);
3
1

The point of declaring delegates in the first place is so that you could call a method without seeing its declaration. That is why you need a different delegate type for each function signature that you are planning to call indirectly through a delegate.

2
  • as you said "calling a method without seeing its declaration". That sounds very interesting but the msdn page I'm reading says we must declare number/type of argument(s) and also return type of method. So how does it work? I'm still not clear about whole delegate thing
    – amit kohan
    Oct 9, 2012 at 1:09
  • @amitkohan Declaring a delegate is not the same as declaring a method. By declaring a delegate you specify what methods can be passed for that delegate without declaring these methods, only their signature (parameter types + the return type). Oct 9, 2012 at 1:21
0

Instead of defining a separate method and then using a delegate variable to point to it, you can shorten the code using an anonymous method.

   class Program{
   delegate void MethodsDelegate(string Message);
   static void Main(string[] args){
   MethodsDelegate method = delegate(string Message){
   Console.WriteLine(Message);
    };
   //---call the delegated method---
 method("Using anonymous method.");
 Console.ReadLine();
  }
}
2
  • Thanks for the time you took to show me this snippet but I'm not following the method we have here. What is its return value? I guess its argument is string so its return value could be void?
    – amit kohan
    Oct 9, 2012 at 1:15
  • @amitkohan because it's return value is void you should note that no value is returned from the anonymous method. Oct 9, 2012 at 1:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.