Reputation: 33491
I have defined a delegate like this:
delegate void processRecord(int a, int b);
now i want to use that to create an anonymous method to supply in a function call. The function is defined as such:
void someFunction(processRecord fcn);
and I want to call someFunction
with an anonymous method, but this I cannot get right:
someFunction(new processRecord(a, b) {
// do stuff
});
How is the correct syntax for something like this?
Upvotes: 3
Views: 627
Reputation: 23626
The correct syntax to declare the call to method with processRecord
parameter is:
someFunction(delegate (int a, int b) {
// use a and b here
});
You can take advantage of lambda syntax invoking your someFunction
, because processRecord
is compatible with Action<int,int>
, like this:
someFunction((a, x) => Console.WriteLine(a + "; " + x));
But in .net framework there already exist generic delegate Action
since .NET 3.5
, which you can use instead of creating your own.
So instead you can simply define your function as
void someFunction(Action<int, int> fcn) {}
then call
someFunction( (a,b) => /*use a and b here*/ );
Upvotes: 6
Reputation: 98740
You can use it if you use deletegate in your someFunction
someFunction(delegate( int a, int b) {
// do some stuff
});
Here is a DEMO
.
Upvotes: 1
Reputation: 203802
Here are some options, all of which do effectively the same thing:
someFunction((a,b) => DoStuff());
someFunction(delegate(int a, int b){ doStuff(); });
someFunction(new processRecord((int a, int b) =>
{
doStuff(); doMoreStuff();
}));
Upvotes: 0
Reputation: 726479
You can call it like this:
someFunction(delegate( int a, int b) {
// do stuff
});
C# compiler will figure out that you are making a delegate processRecord
from the context of the call.
Upvotes: 1