Manually setting the Lazy <T>
I have an object that I create from a web service response. If I get a list of these objects, they will have a minimal amount of information (in the example below, the identifiers Prop1 and Prop2 are returned in the list response). If I get the object by ID, the full set of information is returned, including child objects in Prop3 and Prop4.
public class Foo
{
public Guid ID { get; set; }
public string Prop1 { get; set; }
public string Prop2 { get; set; }
public Lazy<IEnumerable<Bar>> Prop3 { get; }
public Lazy<IEnumerable<Bar2>> Prop4 { get; }
}
What I want to do is use this object in partial construction, but if to access Prop3 or Prop4, call the web service to download a more detailed dataset and populate both Prop3 and Prop4.
If I use Lazy, then I can only fill out each property individually by accessing it. This will result in identical webservice calls to parse a small portion of the response each time. What I want to do is create each Lazy as follows:
Prop3 = new Lazy<IEnumerable<Foo>>(() => LoadDetailedInformation());
private void LoadDetailedInformation()
{
// Get info from web service
Prop3.Value = ParseProp3(response);
Prop4.Value = ParseProp4(response);
}
So, in this alleged Lazy implementation, the function will be called when accessing the lazy object, but will not actually return data. It will do some calculations and initialize all lazy values at once.
Am I better off simply folding my own Lazy, or is there any other way to do this without writing a ton of shell code for each property? One of the classes for which I am doing this contains about 20 objects that should be wrapped so that I do not want to write the actual getters and setters if I succeed.
, Lazy<T>, . A Tuple<Bar, Bar2> :
public Bar Prop3 { get { return lazy.Value.Item1; } }
public Bar2 Prop4 { get { return lazy.Value.Item2; } }
private readonly Lazy<Tuple<Bar, Bar2>> lazy =
new Lazy<Tuple<Bar, Bar2>>(LoadDetailedInformation);
private Tuple<Bar, Bar2> LoadDetailedInformation()
{
...
}
, Tuple DetailedResponse - , . , .