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?
There’s no problem that can’t be solved by adding more abstraction. (*)
The pattern you are repeating over and over again is the “lazy loading” pattern. That pattern is highly amenable to being captured in a type, and in fact, it has been, in version 4 of the framework. Documentation here:
http://msdn.microsoft.com/en-us/library/dd642331.aspx
You could then do something like:
And there you go. The first time
shared.Valueis accessed the value gets loaded; every subsequent time the cached value is used. Extra bonus: this is even threadsafe should the shared value be accessed on multiple threads. (See the documentation for details about precisely what guarantees we make regarding thread safety.)(*) Except of course for the problem “I have too much abstraction.”