As I stated in comments on another answer, the need for a ref parameter is a code smell. First of all, if you're doing this in a method, you're breaking the single responsibility principle, but more importantly, the code is only reusable within your inheritance heirarchy.
There's a pattern to be derived here:
public class LazyInit<T>
where T : class
{
private readonly Func<T> _creationMethod;
private readonly object syncRoot;
private T _instance;
[DebuggerHidden]
private LazyInit()
{
syncRoot = new object();
}
[DebuggerHidden]
public LazyInit(Func<T> creationMethod)
: this()
{
_creationMethod = creationMethod;
}
public T Instance
{
[DebuggerHidden]
get
{
lock (syncRoot)
{
if (_instance == null)
_instance = _creationMethod();
return _instance;
}
}
}
public static LazyInit<T> Create<U>() where U : class, T, new()
{
return new LazyInit<T>(() => new U());
}
[DebuggerHidden]
public static implicit operator LazyInit<T>(Func<T> function)
{
return new LazyInit<T>(function);
}
}
This allows you to do this:
public class Foo
{
private readonly LazyInit<Bar> _bar1 = LazyInit<Bar>.Create<Bar>();
private readonly LazyInit<Bar> _bar2 = new LazyInit<Bar>(() => new Bar("foo"));
public Bar Bar1
{
get { return _bar1.Instance; }
}
public Bar Bar2
{
get { return _bar2.Instance; }
}
}