ctorx ctorx - 1 year ago 90
C# Question

C# Lazy Loaded Automatic Properties

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 this...

private string _SomeVariable

public string SomeVariable
if(_SomeVariable == null)
_SomeVariable = SomeClass.IOnlyWantToCallYouOnce();

return _SomeVariable;

into something different, where I can specify the default and it handles the rest automatically...

public string SomeVariable {get; private set;}

Answer Source

No there is not. Auto-implemented properties only function to implement the most basic of properties: backing field with getter and setter. It doesn't support this type of customization.

However you can use the 4.0 Lazy<T> type to create this pattern

private Lazy<string> _someVariable =new Lazy<string>(SomeClass.IOnlyWantToCallYouOnce);
public string SomeVariable {
  get { return _someVariable.Value; }

This code will lazily calculate the value of _someVariable the first time the Value expression is called. It will only be calculated once and will cache the value for future uses of the Value property