How to pass a method as a parameter to another method in C#?
Hello everyone! I just started learning C# and encountered this problem. I have several methods that do almost the same thing, but with slight differences in logic. For example, I want to apply some operation to an array of numbers: either sum all elements, multiply them, or find the maximum. Instead of writing three separate loops, I would like to write one universal method that takes an "action" (another method) and applies it to the array.
I tried to do it like this:
```csharp
public void ProcessArray(int[] numbers, ??? operation)
{
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] = operation(numbers[i]);
}
}
```
But I don't know what to write instead of `???`. I've heard about delegates, but I don't understand how to properly declare and use them. Can you
No answers yet.
Log in to leave an answer
Blogs