I have a situation where I need to generate a few similar anonymous delegates. Here's an example:
public void Foo(AnotherType theObj)
{
var shared = (SomeType)null;
theObj.LoadThing += () =>
{
if(shared == null)
shared = LoadShared();
return shared.Thing;
};
theObj.LoadOtherThing += () =>
{
if(shared == null)
shared = LoadShared();
return shared.OtherThing;
};
// more event handlers here...
}
The trouble I'm having is that my code isn't very DRY. The contents of each of the event handlers is EXTREMELY similar, and could be easily parameterized into a factory method. The only thing preventing me from doing that is that each delegate needs to share the reference to the shared
variable. I can't pass shared
to a factory method with the ref
keyword, as you can't create a closure around a ref
varaiable. Any ideas?