class with a balance and a Deposit method. - CSharp Custom Type

CSharp examples for Custom Type:class

Introduction

Reading and writing monetary amounts with Account objects.

Demo Code

using System;/*  w  w  w  .jav a2s. c  o m*/
class Account
{
   public string Name { get; set; } // auto-implemented property
   private decimal balance; // instance variable
   public Account(string accountName, decimal initialBalance)
   {
      Name = accountName;
      Balance = initialBalance; // Balance's set accessor validates
   }
   public decimal Balance
   {
      get
      {
         return balance;
      }
      private set // can be used only within the class
      {
         if (value > 0.0m) // m indicates that 0.0 is a decimal literal
         {
            balance = value;
         }
      }
   }
   public void Deposit(decimal depositAmount)
   {
      if (depositAmount > 0.0m) // if the depositAmount is valid
      {
         Balance = Balance + depositAmount; // add it to the balance
      }
   }
}
class AccountTest
{
   static void Main()
   {
      Account account1 = new Account("Mary", 50.00m);
      Account account2 = new Account("Edith", -7.53m);
      Console.WriteLine($"{account1.Name}'s balance: {account1.Balance:C}");
      Console.WriteLine($"{account2.Name}'s balance: {account2.Balance:C}");
      Console.Write("\nEnter deposit amount for account1: ");
      decimal depositAmount = decimal.Parse(Console.ReadLine());
      Console.WriteLine($"adding {depositAmount:C} to account1 balance\n");
      account1.Deposit(depositAmount); // add to account1's balance
      Console.WriteLine($"{account1.Name}'s balance: {account1.Balance:C}");
      Console.WriteLine($"{account2.Name}'s balance: {account2.Balance:C}");
      Console.Write("\nEnter deposit amount for account2: ");
      depositAmount = decimal.Parse(Console.ReadLine());
      Console.WriteLine($"adding {depositAmount:C} to account2 balance\n");
      account2.Deposit(depositAmount); // add to account2's balance
      Console.WriteLine($"{account1.Name}'s balance: {account1.Balance:C}");
      Console.WriteLine($"{account2.Name}'s balance: {account2.Balance:C}");
   }
}

Result


Related Tutorials