'Call multiple Methods(b) within Method(a), and reference variables from Method(a)

I've been writing the same nested for loop over and over with different methods within. The methods always take the array index as their input parameter. So I want to write a method for the nested for loop, which can take different methods as an input parameter. I've never tried to make a method an input parameter. What I have written below doesn't work, but I hope it conveys the intent of what I am trying to do.

    public static void Loop(Func<ModelObject> myMethod)
    {
        for (double PositionX = 0.0; PositionX <= 12000.0; PositionX += 3000.0)
        {
            {
                for (double PositionY = 0.0; PositionY <= 30000.0; PositionY += 6000.0)
                {
                    myMethod(PositionX, PositionY);
                }
            }
        }
    }

It gives me a couple errors:

  1. "There is no argument given that corresponds to the required formal parameter 'PositionX' of 'CreateColumns(double, double)'

  2. 'Delegate 'Func<ModelObject>' does not take 2 arguments'

The methods(b) always return a ModelObject type. However, I guess generics could probably be used if the return type were to change. This is what my methods(b) look like for reference:

    public static ModelObject CreateColumns(double PositionX, double PositionY)
    {
        Beam column = new Beam();
        column.StartPoint = Point(PositionX, PositionY, 0);
        column.EndPoint = Point(PositionX, PositionY, 5000.0);

        column.insert();         
    }

So ultimately, I am trying to call CreateColumns within the Loop method, and have the array index passed in as arguments for CreateColumns:

 Loop(CreateColumns());

This is not working right now. Does someone know how to make this logic work?



Solution 1:[1]

Change the signature of Loop() to account for the two double parameters of myMethod:

 public static void Loop(Func<double, double, ModelObject> myMethod)
 {
        // ...
 }

Call Loop() like this:

Loop(CreateColumns);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1