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.

Searcher
  • 1,845
  • 9
  • 32
  • 45
  • 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. – Jason Mar 12 '12 at 06: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 ;) – Random Dev Mar 12 '12 at 06:49
  • Thanks Mr. Jason. Post it as answer.... :) – Searcher Mar 12 '12 at 06:50

1 Answers1

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

Community
  • 1
  • 1
Jason
  • 6,878
  • 5
  • 41
  • 55