0

I have an object property in a class that I do not want to create until the property is first accessed. I can achieve this with the following code:

private XObject _myObject;
public XObject MyObject
{
    get
    {
        if (_myObject == null)
            _myObject = new XObject(this);

        return _myObject;
    }
}

This in turn can be refactored to:

private XObject _myObject;
public XObject MyObject { get => _myObject ?? (_myObject = new XObject(this)); }

However is it possible to achieve the same result without using a backing field?

I can't use Lazy<T> as 'this' is being passed as an argument.

J45
  • 306
  • 3
  • 11
  • 3
    Is [`Lazy`](https://docs.microsoft.com/en-us/dotnet/framework/performance/lazy-initialization) what you are looking for? – Crowcoder Jun 20 '18 at 11:40
  • Is `public Object MyObject { get; } = new Object();` what you are looking for? – aloisdg Jun 20 '18 at 11:42
  • 1
    @aloisdg: probably not because it doesn't initialize the property on first access but earlier and even if this property is never used. – Tim Schmelter Jun 20 '18 at 11:43
  • Sorry, I can't use Lazy as I need to pass 'this' as an argument to the constructor - I will amend the question – J45 Jun 20 '18 at 11:46
  • @TimSchmelter yes indeed. – aloisdg Jun 20 '18 at 11:47
  • @J45: if you need to pass `this`, does [this](https://stackoverflow.com/a/4414386/284240) answer your question? – Tim Schmelter Jun 20 '18 at 11:49
  • @mjwills - question now updated – J45 Jun 20 '18 at 11:55
  • Would `public class Bob { public Bob() { _myObject = new Lazy(() => new XObject(this)); } private Lazy _myObject; public XObject MyObject { get => _myObject.Value; } }` be acceptable (to be fair, it isn't much better than what you have now)? – mjwills Jun 20 '18 at 11:58

0 Answers0