In C#,
Is there a way to turn an automatic property into a lazy loaded automatic property with a specified default value?
Essentially, I am trying to turn th
Here's my implementation of a solve to your problem. Basically the idea is a property that will be set by a function at first access and subsequent accesses will yield the same return value as the first.
public class LazyProperty
{
bool _initialized = false;
T _result;
public T Value(Func fn)
{
if (!_initialized)
{
_result = fn();
_initialized = true;
}
return _result;
}
}
Then to use:
LazyProperty _eyeColor = new LazyProperty();
public Color EyeColor
{
get
{
return _eyeColor.Value(() => SomeCPUHungryMethod());
}
}
There is of course the overhead of passing the function pointer around, but it does the job for me and I don't notice too much overhead compared to running the method over and over again.