This question already has an answer here:
- what is 'this' constructor, what is it for 4 answers
I am very new to c# and I am working through a textbook. The textbook shows this piece of code:
public class BankAccount
{
// Bank accounts start at 1000 and increase sequentially.
public static int _nextAccountNumber = 1000;
// Maintain the account number and balance for each object.
public int _accountNumber;
public decimal _balance;
// Constructors
public BankAccount() : this(0)
{
}
public BankAccount(decimal initialBalance)
{
_accountNumber = ++_nextAccountNumber;
_balance = initialBalance;
}
// more methods...
I am having trouble understanding this:
public BankAccount() : this(0)
{
}
It looks like the syntax for inheritance, but I guess it isn't because this(0)
is not a class. And I don't think it would make logical sense to inherit from the same class that is being used. It is probably a constructor and the syntax is confusing me.
What does this(0)
mean? Why use this
, is there another way to write it?
Would this be the same?:
public BankAccount()
{
BankAccount(0);
}
I understand the following:
public BankAccount(decimal initialBalance)
{
_accountNumber = ++_nextAccountNumber;
_balance = initialBalance;
}
It appears to be a constructor that accepts a balance value, and sets the account number.
My guess would be that this(0)
is really just executing BankAccount(0)
. If this is true, why bother writing two constructors? BankAccount(0)
seems to work fine.
Can someone explain what this
is in a simple way (new to c#; coming from python)?