@JasonEvans answer is actually a little bit wrong. He mixes up base
with this
.
You can use this
to delegate a constructor call to another constructor within the scope of the class:
public class BankAccount
{
// 1st constructor
public BankAccount()
: this(Guid.NewGuid(), 0, new List<Transaction>(), "")
{
_transactions.Add(new Transaction(0m, 0m, "account created", DateTime.Now));
}
// 2nd constructor
public BankAccount(Guid Id, decimal balance, IList<Transaction> transactions, string customerRef)
{
AccountNo = Id;
_balance = balance;
_transactions = transactions;
_customerRef = customerRef;
}
}
In your example the first constructor delegates it's call to the second constructor, before it executes itself. So in your example the BankAccount
get's initialized with an empty list of Transactions
, when the default constructor is called. After this, the first Transaction
("account created") get's added.