Domanda

Can anyone please explain the purpose of using the syntax like this :

public ClassConstructor() : 
    this(Guid.NewGuid(), 0, new List<Transaction>(), "")
{
}

The code looks like this :

public BankAccount()
    : this(Guid.NewGuid(), 0, new List<Transaction>(), "")
{
    _transactions.Add(new Transaction(0m, 0m, "account created", DateTime.Now));
}

public BankAccount(Guid Id, decimal balance, IList<Transaction> transactions, string customerRef)
{
    AccountNo = Id;
    _balance = balance;
    _transactions = transactions;
    _customerRef = customerRef;
}
È stato utile?

Soluzione

the line below known as constructor initializer

public ClassConstructor(): this(Guid.NewGuid(), 0, new List(), "")

With the above line whenever call to parameter less constructor ClassConstructor() happens it first calls the parameterized constructor this(Guid.NewGuid(), 0, new List(), "") of the same class ClassConstructor and then code/body of the ClassConstructor() get processed

Altri suggerimenti

@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.

It's the same as to write:

public BankAccount()
{
    AccountNo = Guid.NewGuid();
    _balance = 0;
    _transactions = new List<Transaction>();
    _customerRef = "";
    _transactions.Add(new Transaction(0m, 0m, "account created", DateTime.Now));
}

public BankAccount(Guid Id, decimal balance, IList<Transaction> transactions, 
                   string customerRef)
{
    AccountNo = Id;
    _balance = balance;
    _transactions = transactions;
    _customerRef = customerRef;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top