I have a chunk of code that does a “file put” operation inside a moderately complicated piece of retry and try/catch logic. This is working fine, it looks roughly like this:
while (...) {
try {
FilePut(source, destination)
}
catch () {
//Check exception type, possibly re-throw, possibly return, possibly increment
//counters being checked by while loop
}
}
The details of this logic aren’t the issue. But I’m realizing I have several other operations that also need to execute inside this same kind of logic and I want to avoid copy and pasting this logic around my application. I’d like to move it to a function and reuse that function. That function would have to take some sort of reference to the operation to be called, and the try logic would execute that operation (file put, file get, whatever).
This seems like a great place for a delegate, but the problem is, each of these operations has a different signature, so I’m not sure how to be able to write my above logic to be able to call “any” operation.
Is there a good way to do this in C#?
You need an
Actiondelegate to hide all of the different signatures. Something like this:Then, to be able to handle actions with different signatures, you can define a few overloads that take different types of the generic
Action<T>delegates and all of the necessary arguments. These overloads will “curry” the generic action and its arguments to a plainAction:To use:
Also, if you not familiar with them, take a look at the related family of
Funcdelegates as well for good measure.