I am trying to solve the following problem
Declare a generic delegate type Action that has return type void and takes as argument a T value. This is a generalization of yesterday’s delegate type IntAction.
Declare a class that has a method
static void Perform<T>(Action<T> act, params T[] arr) { ... }
This method should apply the delegate act to every element of the array arr. Use the foreach statement when implementing method Perform<T>.
My code looks like this so far:
namespace CSharpexercices
{
public delegate void Action<T>(T value);
public class GenericDelegate
{
static void Perform<T>(Action<T> act, params T[] arr)
{
foreach (T i in arr)
{
act(arr[i]);
}
}
}
}
It’s not working properly and I got lost with the part “this is a generalization of yesterday’s delegate type IntAction.
Could someone help me pretty please 🙂
IntAction is a delegate type (a type that represents a reference to a method, like a function pointer in C++).
Most likely your instructor declared it as follows:
And as thus it represents a method that takes in an
intand returnsvoid. To generalize this, YOUR HOMEWORK asks you to make a generalization of such a delegate. It wants you to create a method that takes an object of ANY TYPE, let’s say type T, and returns void. That’s indeed the delegate System.Action like you used but I think you’re homework asks you to DECLARE that delegate type. This is how you do it (I called the delegate GenericAction and you would use it in exactly the same way you use Action):There is a mistake in your foreach loop. You are trying to assign the result of applying the delegate to an element in an array. But the delegate Action returns void!
To fix this change
to
Feel free to modify your question or comment if you need more clarification.