user3292642
user3292642

Reputation: 761

C# pass parameter to delegate

Hello I have a little problem with C# syntax...

Right now I'm passing four parameters to a method called WriteConfig

 var task = fac.StartNew(() => { vault.WriteConfig(fileName, id, queue, DeleteUploadQueue); });

DeleteUploadQueue is a delegate and gets called with id as parameter inside WriteConfig. What I want to do is pass id to DeleteUploadQueue outside instead of inside WriteConfig so that I dont have to pass id to WriteConfig.

WriteConfig looks like this:

 public void WriteConfig(string fileName, int id, BlockingCollection<byte[]> queue, Action<int> deleteFunc)

But I cannot come up with the correct syntax for this.

Thank you for your help

Upvotes: 0

Views: 94

Answers (3)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

You´re looking from the wrong point. You should provide the arguments for the delegate when you´re calling it, not when you´re defining it. I suppose this happens within your WriteConfig-method:

WriteConfig(string fileName, int id, BlockingCollection<byte[]> queue, Action<int> deleteFunc)
{
    /* ... */
    deleteFunc(id) <------- provide your args here
}

Providing the parameter to your delegate happens at the line marked with <-------. Simply provide the id:

deleteFunc(id);

Upvotes: 0

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249466

Assuming you change the signature to this:

public void WriteConfig(string fileName, BlockingCollection<byte[]> queue, Action deleteFunc)

You could write

var task = fac.StartNew(() => { vault.WriteConfig(fileName, queue,  ()=> DeleteUploadQueue(id)); });

Upvotes: 3

Marc Gravell
Marc Gravell

Reputation: 1062502

sounds like you want

var task = fac.StartNew(() => { vault.WriteConfig(fileName, id, queue,
    () => DeleteUploadQueue(id)); })

so if you also want to change WriteConfig to not take an int id, then you'll need to make the deleteFunc into Action instead of Action<int>, so:

public void WriteConfig(string fileName, BlockingCollection<byte[]> queue,
    Action deleteFunc)

and

var task = fac.StartNew(() => { vault.WriteConfig(fileName, queue,
    () => DeleteUploadQueue(id)); })

Upvotes: 2

Related Questions