bruchowski
bruchowski

Reputation: 5351

Set private field within constructor using set validation from property

So.. How do i validate a private instance variable (field) with a property inside of a constructor?

I have this code that works, but I have a strong feeling this is not how it is supposed to be done:

class Account
    {
        private decimal acctBalance = 0;

        public decimal AcctBalance
        {
            get
            {
                return acctBalance;
            }
            set
            {
                if (acctBalance >= 0)
                    acctBalance = value;
                else
                {
                    Console.WriteLine("Invalid balance, balance set to 0");
                    acctBalance = 0;
                }
            }
        }

        public Account(decimal balance)
        {
            acctBalance = balance;
            AcctBalance = acctBalance;
        }
    }

I just want to make sure that this is the correct way to do it

thanks!

Upvotes: 0

Views: 1772

Answers (1)

Daniel Mann
Daniel Mann

Reputation: 59016

Your approach is mostly right, although there are a couple of issues. I fixed them and annotated the code with comments where I did.

class Account
{
    private decimal acctBalance = 0;

    public decimal AcctBalance
    {
        get
        {
            return acctBalance;
        }
        set
        {
            //modified to check value instead of acctBalance
            if (value >= 0)
                acctBalance = value;
            else
            {
                Console.WriteLine("Invalid balance, balance set to 0");
                acctBalance = 0;
            }
        }
    }

    public Account(decimal balance)
    {
        //redundant! Changing AcctBalance changes acctBalance
        //acctBalance = balance;
        AcctBalance = balance; 
    }
} 

Upvotes: 3

Related Questions