Inner Fields and Lazy Initialization in C#
Posted by: Steven Smith,
on 29 Oct 2011 |
View original | Bookmarked: 0 time(s)
Using lazy initialization in C#, a classs state is set up such that each propertys get method performs a check to see if the underlying field is null. If it is, then it calculates or populates the field before returning it. This is a very simple and common approach, but it requires that the class follows a convention of only accessing the field via the property. Unfortunately, there are no language features that can enforce this, so its possible for errors to creep in. Heres an example of this approach working correctly:
public
class Order
{
// other properties
private Customer _customer;
public Customer Customer
{
get
{
if(_customer == null)
{
_customer = _customerRepository.Get(_customerId);
}
return _customer;
}
public string PrintLabel()
{
return Customer.CompanyName + "\n" + Customer.Address;
}
}
Now heres where this approach can break down. Consider the same class as above, but with a rewritten PrintLabel() method:
public string PrintLabel()
{
return _customer.CompanyName + "\n" + _customer.Address;
}
This code will still compile just fine, but now will very likely result in a NullReferenceException when it attempts to access properties of the _customer, which may not yet be initialized. The solution to this would be to control access to the _customer member. Weve already set its access to private, though, which is as restrictive as we can make it. We could force it to be initialized by moving the work into the classs constructor, but then were losing the benefits of lazy initialization. I wonder if it wouldnt be useful to do something like this instead:
public class Order
{
// other properties
public Customer Customer
{
private Customer _customer; // only accessible within the get() and set() methods of this property
get
{
if(_customer == null)
{
_customer = _customerRepository.Get(_customerId);
}
return _customer;
}
public string PrintLabel()
{
string result = Customer.CompanyName; // ok to access Customer
return result + "\n" + _customer.Address; // compiler error - cannot access _customer from here
}
}
We already have auto-properties in C# that avoid the need for having backing fields in the default case. I think being able to protect access to backing fields so that they can be configured to only be accessible by their property would be quite useful in a number of cases, including this very common one. I also dont believe this would break any existing code or change the language in a way that would make it less easy to understand. What do you think, is this something the C# team should consider adding in a future version of the language?

