1

Hello I have the following code.

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace myConsole { public delegate int showDelegate(); public class addmultipleClass { public int addNumbers(int a, int b) { return (a + b); } public int multiplyNumbers(int a, int b) { return (a * b); } } class Delegate { static void Main(string[] args) { addmultipleClass myObj = new addmultipleClass(); showDelegate add = new showDelegate(myObj.addNumbers); } } } 

It is showing error like this No overload for 'addNumbers' matches delegate 'myConsole.showDelegate'

Why it is showing this error. Whats wrong in my code. Is it not correct way to reference the addNumbers() method.

Why should i use the delegate over here. I can achieve this by using class object. as myObj.addNumbers(10,20); So what is the need for delegate? Please help me. Thank you all.

3
  • 2
    Modify showDelegate to match the parameters of addNumbers: public delegate int showDelegate(int a, int b); Delegates have to match the number and type of parameters in addition to your return type. Commented Mar 12, 2012 at 6:48
  • 1
    why not make this an answer Jason? would surely vote for it - now every other answer will just be "borrowed" from your comment ;) Commented Mar 12, 2012 at 6:49
  • Thanks Mr. Jason. Post it as answer.... :) Commented Mar 12, 2012 at 6:50

1 Answer 1

4

Modify showDelegate to match the parameters of addNumbers:

public delegate int showDelegate(int a, int b); 

Delegates have to match the number and type of parameters in addition to your return type.

The second part of your question is essentially asking: "why delegates?". For that answer, I suggest you look at other Stack Overflow posts for much more detailed and precise answers, for a start:

Delegates, Why? when & why to use delegates? The purpose of delegates

Sign up to request clarification or add additional context in comments.

1 Comment

@Jason.. can you please look the question again

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.