This is simplified setup – I have API (I have n o control on the API), which exposes a Func property like this:
public Func<dynamic, MyClass> FuncProperty { get; set; }
Usually it’s used like this:
api.FuncProperty = s =>
{
do1();
do2();
return new MyClass(); //simplified
}
Similar code is used all over the place (of course the content in {} is different), and I want to add common functionality to all these, I’d like to create a “wrapper” method, which I can use like this:
api.FuncProperty = MyWrapperMethod(
s =>
{
do1();
do2();
return new MyClass();
});
I know I can edit all these calls to look like:
api.FuncProperty = s =>
{
DoMyCommonFunctionality();
//... as before
}
But if my common functionality is something like:
using(var disposable = SetSomeState())
{
//the stuff which previously was in the lambda
}
then, using the latter approach is kind of ugly.
That’s why even if it’s only for learning purposes, how should my wrapper’s method signature look like? And how should I use it?
If I understand you right, it should also return a
Func<dynamic, MyClass>, like this:That’s an example with the
usingstatment you wanted.Note that calling
MyWrapperMethoddoes not call the delegate you pass into it. Instead, it returns a delegate which, when called, will call the delegate you passed. This sort of deferred execution can be confusing, but I believe it’s what you want here.