1

I have two classes, first:

    public class A
    {
        public delegate void Function();

        public string name;
        public Function function;

        public A(string name, Function function)
        {
            this.name = name;
            this.function = function;
        }
    }

And in second:

    public class B
    {
        public delegate void Function();
        List<A> ListA;

        // somewhere in function
        void F()
        {
            ListA[i].function();
        }
        // ---

        public void AddA(string name, Function function)
        {
            ListA.Add(new A(name, function)); // error here
        }
    }

It throws these errors:

Error   2   Argument 2: cannot convert from 'App.B.Function' to 'App.A.Function'
Error   1   The best overloaded method match for 'App.A.A(string, App.A.Function)' has some invalid arguments

How to solve this?

svick
  • 236,525
  • 50
  • 385
  • 514
Neomex
  • 1,650
  • 6
  • 24
  • 38
  • The answers are good enough.. and also check this http://www.codeproject.com/Articles/71154/C-Delegates-101-A-Practical-Example – Nagaraj Tantri May 12 '12 at 15:33

2 Answers2

7

You have declared Function delegate twice, one inside class A and one inside B.
So they're two different types, one called App.B.Function and the other called App.A.Function.

If you want to share this delegate with both the classes, just declare it once and out of the scope of the classes (i.e. in the assembly scope) e.g.:

public delegate void Function();

public class A
{
    public string name;
    ...
}

public class B
{
    List<A> ListA;
    ...
}

However, in the System namespace exist a certain number of generic delegates that can be used to represent various functions. Have a look at System.Action<> and System.Func<> types.

digEmAll
  • 56,430
  • 9
  • 115
  • 140
0

The reason it happen is that Function is declared twice, once in each clases

Servy
  • 202,030
  • 26
  • 332
  • 449
gabba
  • 2,815
  • 2
  • 27
  • 48
  • 1
    I think you meant it's declared once in each class, not twice in both (which would be four total). – Servy May 12 '12 at 16:53