When I want to make use of Lazy<T>
and need to refer to this
I need to write a lot of boilerplate code:
// the private member
private Lazy<SubEventCollection> _SubEvents;
public Event()
{
// needs to be initialized in the constructor because I refer to this
_SubEvents = new Lazy<SubEventCollection3>(CreateSubEvents);
}
// the "core" body
private SubEventCollection CreateSubEvents()
{
SubEventCollection3 collection;
using ( var stream = new MemoryStream(DbSubEventsBucket) )
collection = Serializer.Deserialize<SubEventCollection3>(stream);
collection.Initialize(this);
return collection;
}
// The final property
public SubEventCollection SubEvents => _SubEvents.Value;
Is this all really necessary? It feels like too much boilerplate and everything all over the place. Are there any shortcuts that read a bit nicer with not that much seperate boilerplate around? I could probably move the body to the constructor, but I wouldn't like that either - i.e. you move a lot of important logic into your constructor.
My preferred way would be something similar like Knockout.js / TypeScript.
subEvents = ko.lazyComputed(() =>
{
SubEventCollection3 sub_events;
using ( var stream = new MemoryStream(DbSubEventsBucket) )
sub_events = Serializer.Deserialize<SubEventCollection3>(stream);
sub_events.Initialize(this);
return sub_events;
})
Not a lot of 'moving parts' here and super concise. What other options are there? I notice that I often fall back to a manual 'lazy' construction.
private SubEventCollection _SubEvents;
public SubEventCollection SubEvents
{
get
{
if ( _SubEvents == null )
{
using ( var stream = new MemoryStream(DbSubEventsBucket) )
collection = Serializer.Deserialize<SubEventCollection3>(stream);
collection.Initialize(this);
_SubEvents = collection;
}
return _SubEvents;
}
}
At least this has less 'moving parts' then the Lazy way, and I can keep everything together (do not have to put half the logic in the constructor). Of course this has a lot of other disadvantages, like that it's not thread-safe.
Am I still missing other alternatives?
PS I assume there are in a two different answers - one for true thread-safe lazy loading and one for just a concise version where you don't care if it accidently gets called twice.