Bart Friederichs
Bart Friederichs

Reputation: 33491

C# delegate in function call

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

Answers (5)

Ilya Ivanov
Ilya Ivanov

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

Soner G&#246;n&#252;l
Soner G&#246;n&#252;l

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

Servy
Servy

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

daryal
daryal

Reputation: 14919

processRecord t = (q,w) =>
        {
            int n = q+w;
        };
        someFunction(t);

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

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

Related Questions