Properties and Encapsulation
Encapsulated State
Methods can change private state while the class controls what is allowed.
Encapsulated State
EncapsulatedState.cs
using System;
class Wallet
{
private int cents;
public int Cents
{
get { return cents; }
}
public void Deposit(int amount)
{
if (amount > 0)
{
cents += amount;
}
}
public bool Spend(int amount)
{
if (amount <= cents)
{
cents -= amount;
return true;
}
return false;
}
}
class Program
{
static void Main()
{
int spend = ;
Wallet wallet = new Wallet();
wallet.Deposit(50);
bool paid = wallet.Spend(spend);
Console.WriteLine($"spend={spend}");
Console.WriteLine($"paid={paid}");
Console.WriteLine($"remaining={wallet.Cents}");
}
}
using System;
class Wallet
{
private int cents;
public int Cents
{
get { return cents; }
}
public void Deposit(int amount)
{
if (amount > 0)
{
cents += amount;
}
}
public bool Spend(int amount)
{
if (amount <= cents)
{
cents -= amount;
return true;
}
return false;
}
}
class Program
{
static void Main()
{
int spend = ;
Wallet wallet = new Wallet();
wallet.Deposit(50);
bool paid = wallet.Spend(spend);
Console.WriteLine($"spend={spend}");
Console.WriteLine($"paid={paid}");
Console.WriteLine($"remaining={wallet.Cents}");
}
}
using System;
class Wallet
{
private int cents;
public int Cents
{
get { return cents; }
}
public void Deposit(int amount)
{
if (amount > 0)
{
cents += amount;
}
}
public bool Spend(int amount)
{
if (amount <= cents)
{
cents -= amount;
return true;
}
return false;
}
}
class Program
{
static void Main()
{
int spend = ;
Wallet wallet = new Wallet();
wallet.Deposit(50);
bool paid = wallet.Spend(spend);
Console.WriteLine($"spend={spend}");
Console.WriteLine($"paid={paid}");
Console.WriteLine($"remaining={wallet.Cents}");
}
}
encapsulation
Encapsulation keeps state changes inside the object that owns the state.