You may want to use Lazy<T>
, it's cleaner syntax and less error-prone than double check locking.
It helps you create an object which is initialized only once when being first accessed (lazy initialization), I think that the syntax is quite self-explanatory, some usage examples are in this MSDN article, I'll cite the example:
class Customer
{
private Lazy<Orders> _orders;
public string CustomerID {get; private set;}
public Customer(string id)
{
CustomerID = id;
_orders = new Lazy<Orders>(() =>
{
// You can specify any additonal
// initialization steps here.
return new Orders(this.CustomerID);
});
}
public Orders MyOrders
{
get
{
// Orders is created on first access here.
return _orders.Value;
}
}
}