Search code examples
c#optimizationinterfacepropertiesinitialization

Better ways to initialize property backing field once on first call


I have interface IDataHolder that defines property holding some data and multiple classes that inherits that interface. Each objects can have unique data with type DataType which has child classes. But data needs to be generated first before accessing it.

When creating new classes using that interface I always need to generate data somewhere in the code and it became repetitive task. Right now I have two options:

private DataType data;
public DataType Data {get => data; set => data = value;}

public void Init()
{
    Data = GenerateData();
}

Or more favorable...

private DataType data;
public DataType Data
{
    get => data ? data : data = GenerateData();
    set => data = value;
}

So the question is: Is there a better way to create property that assigns backing field once on first call?

Full code example:

public interface IDataHolder
{
    DataType Data { get; set;}
}
public class Base
    {
        public T <T>GenerateData()
        { 
            // data generation
        }
    }
public class Derived : Base, IDataHolder
    {
        private DataType data;
        public DataType Data
        {
            get => data ? data : data = GenerateData();
            set => data = value;
        }
    }


Solution

  • You can use Lazy<>.

    private Lazy<DataType> data = new Lazy<DataType>(GenerateData);
    
    public DataType Data
    {
        get => data.Value;
    } 
    

    The first time data.Value is called, the Value will be assigned from the result of GenerateData, every other time, it will just return the value.