C# – How make arrays of delegates and use this array

c++delegates

I have to write class Eve to make some code below:

class MainClass
  {    int sum = 5;
    public  void add (int x)
    {
      sum += x;
    }
    public static void write (int x)
    {
      Console.WriteLine("x = " + x);
    }
    public static void Main (string[] args)
    {
      Eve p = new Eve();
      MainClass m = new MainClass(); 
      p.registrate(m.add);
      p.registrate(write);
      p.registrate (delegate (int x) { 
                      System.Console.WriteLine(" I have {0} ", x);
                    }); 
      p.registrate (x => System.Console.WriteLine (" Square : {0} ", x * x));
      p.run(10);
      p.run(5);
                  Console.WriteLine(" Sum is {0} ", m.sum);
    }
  }

Output:

x = 10

I have 10

Square : 100

x = 5

I have 5

Square : 25

Sum is 20

So think I have to use delegates. And method registarte should add delegate to array of delegates.

I wrote code like this but i dint sure is wright.

 public class Eve
    {
        int i;
        public Eve()
        {
            i = 0;
        }
        public delegate void ComputeDelegate(int x);

        ComputeDelegate[] delegates = new ComputeDelegate[2];

        public void registrate(ComputeDelegate a)
        {
            if (i == 2) i = 0;
            delegates[i] += a;
            i++;
        }

        public void run()
        {
            //delegates[0].;
        }
}
        public class MainClass
        {
            int sum = 5;
            public void add(int x)
            {
                sum += x;
            }
            public void write(int x)
            {
                Console.WriteLine("x = " + x);
            }
            static void Main()
            {
                Eve proc1 = new Eve();
                MainClass m = new MainClass();

                proc1.registrate(m.add);
                proc1.registrate(m.write);


            }
        }
    }

I have problem how I have to write method run? Or this same but in another way how i can lunch method wich is in delegate array?

Best Solution

As you want to add delegates, a list would be better than an array. There are generic delegate types that you can use instead of creating a custom delegate type:

List<Action<int>> delegates = new List<Action<int>>();

To register a delegate, just add it to the list:

public void registrate(Action<int> a) {
  delegates.Add(a);
}

To use the delegates, just call them by putting parentheses after them. The same syntax as with a regular method. Example:

int input = 5;
foreach (Action<int> a in delegates) {
  a(input);
}