I'm trying to find a neat way to trigger a loading mechanism when one of several getters is first accessed. My first thoughts are about something like this:
public class Customer {
private bool loaded = false;
public int PK { get; set; }
public string Email { get; set; }
public string Name { get { if (!loaded) loadData(); return _name; } set { ... } }
public string Street { get { if (!loaded) loadData(); return _street; } set { ... } }
public string City { get { if (!loaded) loadData(); return _city; } set { ... } }
}
In short, in this example every Customer exists with its base data PK and Email until one of the other properties is accessed.
This would mean much duplicate code, increasing with the complexity of the class. Is there a way to create some kind of inheritance for these properties?
Something like this, but I don't think this is possible:
private void checkData() { if (!loaded) loadData(); }
public string Name:checkData { get; set; }
public string Street:checkData { get; set; }
public string City:checkData { get; set; }
Another way might be possible through reflection, but as I'm not experienced with it I don't know where to start here.
Any hints are deeply appreciated! ;-)
You can use the Lazy<T> class to wrap the secondary properties.
This way loadData will only execute if any of the secondary getters is called and won't be executed more than once.
public class Customer
{
public int PK { get; set; }
public string Email { get; set; }
public string Name { get { return data.Value.Name; } }
public string Street { get { return data.Value.Street; } }
public string City { get { return data.Value.City; } }
public Customer()
{
data = new Lazy<CustomerData>(loadData);
}
private CustomerData loadData()
{
...
}
private struct CustomerData
{
public string Name, Street, City;
}
private Lazy<CustomerData> data;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With