How to count in anonymous method?

133 Views Asked by At

I have this an implementation of class IntList. I'm am supposed to: Use the capability of the anonymous methods to refer to a local variable in their enclosing method and the defined "Act"-method to compute the sum of an IntList’s elements (without writing any loops yourself). This is what I have done so far, but I doubt that it is correct. Any suggestions and explanations will help me here

What is my anonymous method's enclosing method in this case?

public delegate bool IntPredicate(int x);
public delegate void IntAction(int x);


class IntList : List<int>
{
    public IntList(params int[] elements) : base(elements)
    {

    }

    public void Act(IntAction f)
    {
        foreach(int i in this)
        {
            f(i);
        }
    }

    public IntList Filter(IntPredicate p)
    {
        IntList res = new IntList();
        foreach (int i in this)
        {
            if (p(i))
            {
                res.Add(i);
            }
        }
        return res;
    }

}

class Program
{
    static void Main(string[] args)
    {
        // code here
        IntList xs = new IntList();
        // adding numbers, could be random. whatever really. Here just 0..29
        for(int i =0; i<30; i++)
        {
            xs.Add(i);
        }

        int total = 0;
        xs.Act(delegate (int x)
                        {
                            total = total + x;
                            Console.WriteLine(total);
                        }
               );
        Console.ReadKey();
    }
}
1

There are 1 best solutions below

0
robbpriestley On

I think this part is the "anonymous method" (because it is defined inline and doesn't have a method name):

delegate (int x)
{
    total = total + x;
    Console.WriteLine(total);
}

I think the "enclosing method" is Main().

I think the "local variable" is most likely total.

I ran your code and it seems correct to me.