I am getting a warning from the compiler about my code. I don’t know why because I have checked it in the property setter. If I check this in the constructor, the warning disappears, but then I have to write the same code twice, which is not good. Can someone explain to me how I should write this class? I want to know what is the right way to do this?
public class BankAccount
{
private string _owner;
private decimal _balance;
public BankAccount(string owner, decimal balance)
{
// The compiler warning is gone if I check the values here,
// but this leads to code duplication.
this.Owner = owner;
this.Balance = balance;
}
public string Owner
{
get
{
return _owner;
}
set
{
if (value is null)
{
throw new ArgumentNullException("Owner name you want to set is null");
}
_owner = value;
}
}
public decimal Balance
{
get
{
return _balance;
}
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException("Balance should not be negative.");
}
_balance = value;
}
}
public void Deposit(decimal amount)
{
if (amount < 1)
{
throw new ArgumentOutOfRangeException("Amount should not be negative");
}
this.Balance += amount;
}
public void Withdraw(decimal amount)
{
if (amount < 1)
{
throw new ArgumentOutOfRangeException("Amount should not be negative");
}
this.Balance -= amount;
}
}
New contributor
user25109278 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.