CSharp examples for Custom Type:class
Implement a Investment Account as a form of account
using System;//from w ww.ja v a 2 s .c o m public class Account // The base class. { public static int _nextAccountNumber = 1000; public int _accountNumber; public decimal _balance; public void InitAccount() { InitAccount(0); } public void InitAccount(decimal initialBalance) { _accountNumber = ++_nextAccountNumber; _balance = initialBalance; } public decimal Balance { get { return _balance;} } public void Deposit(decimal amount) { if (amount > 0) { _balance += amount; } } public decimal Withdraw(decimal withdrawal) { if (Balance <= withdrawal) // Use Balance property. { withdrawal = Balance; } _balance -= withdrawal; return withdrawal; } public string ToAccountString() { return String.Format("{0} - {1:C}", _accountNumber, Balance); } } public class InvestmentAccount : Account // The subclass. { public decimal _interestRate; public void InitInvestmentAccount(decimal interestRate) { InitInvestmentAccount(0, interestRate); } public void InitInvestmentAccount(decimal initialBalance, decimal interestRate) { InitAccount(initialBalance); // Note call to base class. this._interestRate = interestRate / 100; } public void AccumulateInterest() { _balance = Balance + (decimal)(Balance * _interestRate); } public string ToInvestmentAccountString() { return String.Format("{0} ({1}%)", ToAccountString(), _interestRate * 100); } } public class Program { public static void Main(string[] args) { Account ba = new Account(); ba.InitAccount(100M); // M suffix indicates decimal. ba.Deposit(100M); Console.WriteLine("Account {0}", ba.ToAccountString()); InvestmentAccount sa = new InvestmentAccount(); sa.InitInvestmentAccount(100M, 12.5M); sa.AccumulateInterest(); Console.WriteLine("Account {0}", sa.ToInvestmentAccountString()); } }