A public constructor initializes private instance variable balance through public property.
using System;
public class Account
{
private decimal balance;
public Account( decimal initialBalance )
{
Balance = initialBalance;
}
public void Credit( decimal amount )
{
Balance = Balance + amount;
}
public decimal Balance
{
get
{
return balance;
}
set
{
if ( value >= 0 )
balance = value;
}
}
}
public class AccountTest
{
public static void Main( string[] args )
{
Account account1 = new Account( 5.00M );
Account account2 = new Account( -7.53M );
Console.WriteLine( "account1 balance: {0:C}",account1.Balance );
Console.WriteLine( "account2 balance: {0:C}\n",account2.Balance );
decimal depositAmount;
Console.Write( "Enter deposit amount for account1: " );
depositAmount = Convert.ToDecimal( Console.ReadLine() );
Console.WriteLine( "adding {0:C} to account1 balance\n",depositAmount );
account1.Credit( depositAmount );
Console.WriteLine( "account1 balance: {0:C}",account1.Balance );
Console.WriteLine( "account2 balance: {0:C}\n",account2.Balance );
Console.Write( "Enter deposit amount for account2: " );
depositAmount = Convert.ToDecimal( Console.ReadLine() );
Console.WriteLine( "adding {0:C} to account2 balance\n",depositAmount );
account2.Credit( depositAmount );
Console.WriteLine( "account1 balance: {0:C}", account1.Balance );
Console.WriteLine( "account2 balance: {0:C}", account2.Balance );
}
}
Related examples in the same category