'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
Solution 1:[1]
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)); })
Solution 2:[2]
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);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Marc Gravell |
| Solution 2 | marc_s |
