I am looking if there is elegant way to make sure when property is accessed first time, associated backing field is set. For example, I end up lot with below code paradigm to address this :
private Address _address;
public Address Address
{
get
{
if (_address == null)
{
_address = GetAddress();
}return _address;
}
}
Unless error prone or time consuming, I would suggest populating the property in the constructor. Otherwise, I suggest using Lazy<T>
to do it, for thread safety:
public class MyClass
{
private Address _address;
public MyClass()
{
_address = GetAddress();
}
public Address Address {get {return _address;}}
}
Using Lazy<T>
:
public class MyClass
{
private Lazy<Address> _address;
public MyClass()
{
_address = new Lazy<Address>(() => GetAddress());
}
public Address Address {get {return _address.Value;}}
}
Starting with c#6, you can have an auto-implemented property like this, but then you have to make the GetAddress()
method static
:
public Address Addgress {get;} = GetAddress();
That will translate to something like the first option I've shown - See SharpLab demo.