I have some auto-instantiation code which I would like to apply to about 15 properties in a fairly big class. The code is similar to the following but the type is differ
You could implement lazy initialization in a manner similar to this:
public class Lazy where T : new()
{
private T _value;
private bool _isInitialized;
private T GetValue()
{
if (!_isInitialized)
{
_value = new T();
_isInitialized = true;
}
return _value;
}
public static implicit operator T (Lazy t)
{
return t.GetValue();
}
}
which would allow you to write code like this:
private Lazy _lazyCt = new Lazy();
public ComplexType LazyCt
{
get { return _lazyCt; }
}
The specifics of the initialization are irrelevant, I wrote it like this to show that you can make it transparently convertible to the non-lazy version, and perform the initialization on the first conversion. :)