Home » c# » C# Lazy Loaded Automatic Properties

C# Lazy Loaded Automatic Properties

Posted by: admin November 29, 2017 Leave a comment

Questions:

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
{
     get
     {
          if(_SomeVariable == null)
          {
             _SomeVariable = SomeClass.IOnlyWantToCallYouOnce();
          }

          return _SomeVariable;
     }
}

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

[SetUsing(SomeClass.IOnlyWantToCallYouOnce())]
public string SomeVariable {get; private set;}
Answers:

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

Questions:
Answers:

Probably the most concise you can get is to use the null-coalescing operator:

get { return _SomeVariable ?? (_SomeVariable = SomeClass.IOnlyWantToCallYouOnce()); }

Questions:
Answers:

There is a new feature in C#6 called Expression Bodied Auto-Properties, which allows you to write it a bit cleaner:

public class SomeClass
{ 
   private Lazy<string> _someVariable = new Lazy<string>(SomeClass.IOnlyWantToCallYouOnce);

   public string SomeVariable 
   {
      get { return _someVariable.Value; }
   }
}

Can now be written as:

public class SomeClass
{
   private Lazy<string> _someVariable = new Lazy<string>(SomeClass.IOnlyWantToCallYouOnce);

   public string SomeVariable => _someVariable.Value;
}

Questions:
Answers:

Not like that, parameters for attributes must be constant in value, you cannot call code (Even static code).

You may however be able to implement something with PostSharp’s Aspects.

Check them out:

PostSharp

Questions:
Answers:

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<T>
{
    bool _initialized = false;
    T _result;

    public T Value(Func<T> fn)
    {
        if (!_initialized)
        {
            _result = fn();
            _initialized = true;
        }
        return _result;
    }
 }

Then to use:

LazyProperty<Color> _eyeColor = new LazyProperty<Color>();
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.

Questions:
Answers:

I don’t think this is possible with pure C#. But you could do it using an IL rewriter like PostSharp. For example it allows you to add handlers before and after functions depending on attributes.

Questions:
Answers:

https://github.com/bcuff/AutoLazy uses Fody to give you something like this

public class MyClass
{
    // This would work as a method, e.g. GetSettings(), as well.
    [Lazy]
    public static Settings Settings
    {
        get
        {
            using (var fs = File.Open("settings.xml", FileMode.Open))
            {
                var serializer = new XmlSerializer(typeof(Settings));
                return (Settings)serializer.Deserialize(fs);
            }
        }
    }

    [Lazy]
    public static Settings GetSettingsFile(string fileName)
    {
        using (var fs = File.Open(fileName, FileMode.Open))
        {
            var serializer = new XmlSerializer(typeof(Settings));
            return (Settings)serializer.Deserialize(fs);
        }
    }
}