views:

80

answers:

2

Is it possible to have a generic method that requires a delegate(?) for a method or just a code block to be passed in as a parameter?

Say I have AddJob() and AddJob2(). I want these passed into a Generic method that runs some skeleton code but then executes the AddJob or AddJob2.

Thanks!

Edit:
I'm on .net 2.0.

+7  A: 

Sure:

public void AddJob(string jobName) { ... }
public void AddJob2(string jobName) { ... }

public void RunAddJob(Action addJob)
{
    ...
    addJob();
}

static void Main()
{
    RunAddJob(() => AddJob("job1"));
    RunAddJob(() => AddJob2("job2"));
}

Edit: the non-generic System.Action is new in .NET 3.5. For .NET 2.0, you can assume:

public delegate void Action();
Tim Robinson
Is it possible to not supply jobName if you don't know what parameters are passed into the functions AddJob and AddJob2?Thanks
Adam Witko
@Adam if I've understood correctly, I can amend the answer to demonstrate
Tim Robinson
...although the `RunAddJob` method in the example no longer needs to be generic if I do that.
Tim Robinson
Yeah what you'e changed it too is what I'm looking for I think!Is Action still required though? not Delegate?
Adam Witko
Not Delegate: you need to deal with a concrete delegate type. `System.Delegate` is the abstract base class for all delegate types. `System.Action` and `System.Func` are various concrete delegate types, for different sets of parameter and return types.
Tim Robinson
OK that makes sense, but isn't Action a generic itself?Well what I mean it's definition is Action<T>?
Adam Witko
There's a bunch of different `Action` delegates, with the same name but with different numbers of generic parameters. Here I used `Action`, which accepts no parameters and returns nothing, so there's no need for it to be generic. There's also `Action<T>`, which accepts one parameter; the type of parameter is generic. Likewise `Action<T1, T2>`, `Action<T1, T2, T3>` etc. All of these are treated as different types even though they have the same name.
Tim Robinson
Sorry saw that, believe it's because I'm on .net 2.0 which doesn't have just Action!
Adam Witko
Apologies - none of this makes unless you have the docs for .NET 3.5 or above in front of you.
Tim Robinson
@Adam: I added that you were on .NET 2.0 to the question. I hope that doesn't bother you.
R. Bemrose
+4  A: 

Most of the Enumerable class (for LINQ) works like that.

T MyFunc<T>(T t, Func<T, T> addjob)
{
    return addjob(t);
}


MyFunc(5, i => i + 10);
James Curran