Why after implementing get in field property I can't initialize that field in constructor?

Viewed 22

I am doing tutorial from MSDN and I was following it step by step, after implementing get method in Balance property I got an error in constructor when I try to initialize that field:

error CS0200: Unable to assign value to property or indexer "BankAccount.Balance" - it is read only

If I good interprets it tells me that I do not have set method in property. But why i can initialize Number field if it also do not have set method.

Here is code:


public class BankAccount{
    private static int accountNumberSeed = 1234567890;

    public string Number {get;}
    public string Owner {get; set;}

    public decimal Balance{
        get{
            decimal balance = 0;
            foreach (var item in allTransactions){
                balance += item.Amount;
            }

            return balance;
        }

    }

    public BankAccount(string name, decimal initialBalance){
        this.Owner = name;
        this.Balance = initialBalance;
        this.Number = accountNumberSeed.ToString();
        ++accountNumberSeed;
    }

    private List<Transaction> allTransactions = new List<Transaction>();

    public void MakeDeposit(decimal amount, DateTime date, string note){
        if (amount <= 0){
            throw new ArgumentOutOfRangeException(nameof(amount), "Amount of deposit must be positive");
        }
        var deposit = new Transaction(amount, date, note);
        allTransactions.Add(deposit);    
    }

    public void MakeWithdrawal(decimal amount, DateTime date, string note){ }


}

0 Answers
Related