I have a property within my class that I would expect to set itself when a new instance of the class is created, but it doesn’t, why?
public class RecurlyData
{
private readonly string _accountCode;
//Default constructor
public RecurlyData(int accountCode)
{
_accountCode = accountCode.ToString();
}
public RecurlyAccount Account { get { return GetAccount(); } }
private RecurlyAccount GetAccount()
{
var account = RecurlyAccount.Get(_accountCode);
account.BillingInfo = RecurlyBillingInfo.Get(account.AccountCode);
return account;
}
}
I am calling it like this:
private List<RecurlyData> _recurlyData;
_recurlyData.Add(new RecurlyData(1079));
I believe what you are expecting to happen is that
GetAccount();will be called when the object is constructed.That is not how properties work.
A property’s getter acts just like a method, so in fact your property
Does the exact same thing as the
GetAccountmethod.Calling:
Is 100% identical to:
If that method causes some visible side-effects (which I imagine it does, otherwise it wouldn’t matter whether it gets called in the constructor or not) then it most likely should not be in a
getproperty.Every time that
Accountis accessed, the method will get called, so saying:The method
GetAccountwas called twice. The value isn’t saved unless you write code to save it somewhere.@pstrjds’s answer should give you the behaviour you want, but as a slight alternative, if you don’t like needing that private backing field, you can also write:
The result is almost exactly the same, with the exception that it’s only
privateand notreadonlyso you could set it from somewhere other than the constructor. I do personally find it cleaner.