<aside> Properties and instance variables are two fundamental ways to store and manage data in C# classes. Understanding when to use each is crucial for writing maintainable code.
</aside>
public class BankAccount
{
// Auto-implemented properties
public string AccountNumber { get; private set; }
public decimal Balance { get; private set; }
// Property with validation
private string _ownerName;
public string OwnerName
{
get { return _ownerName; }
set
{
if (string.IsNullOrEmpty(value))
throw new ArgumentException("Name cannot be empty");
_ownerName = value;
}
}
public BankAccount(string accountNumber, string ownerName)
{
AccountNumber = accountNumber;
OwnerName = ownerName;
Balance = 0;
}
public void Deposit(decimal amount)
{
if (amount > 0)
Balance += amount;
}
}
public class BankAccount
{
// Private instance variables
private string _accountNumber;
private string _ownerName;
private decimal _balance;
public BankAccount(string accountNumber, string ownerName)
{
_accountNumber = accountNumber;
_ownerName = ownerName;
_balance = 0;
}
// Methods to access instance variables
public string GetAccountNumber()
{
return _accountNumber;
}
public void SetOwnerName(string name)
{
if (string.IsNullOrEmpty(name))
throw new ArgumentException("Name cannot be empty");
_ownerName = name;
}
public decimal GetBalance()
{
return _balance;
}
public void Deposit(decimal amount)
{
if (amount > 0)
_balance += amount;
}
}