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.