(C# Language) Practice Exercise in C# - static and const

This exercise is an exercise just for the sake of practice in static and consts in a class. Create a class called CBankAccount that contains a static member to hold the name of the bank, a constant member to store the minimum balance (100) that a customer has to maintain, another constant member for rate of interest (5) and a yet another constant member for periodicity (4 months) of applying interest. Also add an instance member to hold the balance of a customer in dollars. Add a static constructor to initialize the name of the bank by obtaining input from the user. Add a static function called RenameBank that can be used to give a new name to the bank. Add two functions called Withdraw(int amount) and Deposit(int amount) that update the balance after a successful transaction and print it. Also add a function AddInterest() that calculates simple interest for four months and updates the balance. Test the class in Main.
(Rev. 03-Dec-2022)

Categories | About |     |  

Parveen,

Objectives of this Exercise

This exercise introduces you to

  1. static members, static constructor and static functions
  2. const members
  3. Null coalescing operator(??)
  4. DRY principle
  5. Math.Round function

Video Explanation (see it happen!)

Please watch the following youtube video:

The Solution

Create a C# .NET Core console project as usual. Add a class called CBankAccount. You can obtain the completed project from the downloads attached to this video. Now I will discuss the class.

Add five data members as per the specifications of this question.

Next we have to add a static constructor to set the name of the bank. The same code has to be repeated in the RenameBank function. So we can create a static function getBankName to obtain the name from the user. The function uses Console.ReadLine to obtain the string entered by the user. The function console readline can return null. So we have used the null coalescing operator (??) to return a default name if null is returned.

Now we can add a static constructor where the static member s_bankName is set.


// the class 

// project is attached as a  
// download to the video tutorial 

internal class CBankAccount
{
  // five data members/fields 
  static String s_bankName;

  const int s_minimumBalance = 100;

  const float s_rateOfInterest = 5.0f;

  const float s_interestPeriodicity = 4;

  int _balance = 0;

  // will be used by 2 functions 
  // so DRY - do not repeat yourself 
  static String getBankName()
  {
    Console.Write("Enter name of the bank: ");

    // null coalescing operator (??) 
    // helps return a default value 
    // instead of a null 
    return Console.ReadLine() ?? "Un-named";
  }

  static CBankAccount()
  {
    s_bankName = getBankName();
  }

  public static void RenameBank()
  {
    s_bankName = getBankName();
  }

  void printBalance()
  {
    Console.WriteLine($"Balance is ${_balance}");

    Console.WriteLine($"Thanks from {s_bankName}");

    Console.WriteLine("=====================\n");
  }

  bool canWithdraw(int amount)
  {
    int expectedBalance = _balance - amount;

    if ((amount <= 0)
          ||
          (expectedBalance < s_minimumBalance)
      )
    {
      Console.WriteLine("No balance or bad input. TXN Failed.");

      return false;
    }

    return true;
  }

    
  public void Withdraw(int amount)
  {
    if (!canWithdraw(amount))
      return;

    // update the balance 
    _balance -= amount;

    Console.WriteLine($"Withdrawl of ${amount}");

    printBalance();

  }

  public void Deposit(int amount)
  {
    // update the balance 
    _balance += amount;

    Console.WriteLine($"Amount deposited ${amount}");

    printBalance();

  }

  public void AddInterest()
  {
    float interest = 
      (_balance * s_rateOfInterest * s_interestPeriodicity) / 1200.0f;

    Console.WriteLine($"Interest added ${interest}");

    _balance += Convert.ToInt32(Math.Round(interest));

    printBalance();
  }

}

The same call can be added to the RenameBank function also. We could have avoided the getBankName function and repeated the two lines in both the constructor and the RenameBank function. But experts suggest that we should repeat as little code as possible. This is called DRY principle.

After this we have added printBalance function to print the balance. Notice again that this function will be called whenever a transaction takes place. It will again help us avoid pasting these statements again and again. We have again followed the DRY principle.

Another function that we need to add is a function called canWithdraw. This function checks if minimum balance will be maintained after a withdrawl. It uses a basic if condition to make the checks.

Next we have added a public function called Withdraw(int) as per the specifications. The function checks if withdrawl is possible. Then it updates the balance and uses the printBalance function to display the balance after this transaction.

We have similarly added the Deposit(int) function.

Finally, the AddInterest function calculates the interest. The interest is then rounded to the nearest integer by using Math.Round function.

The Main Function

Open the solution explorer and then the Program.cs file.

// Program.cs 
// top level statements 
// Main function 
// project is attached as a 
// download to the video tutorial 
CBankAccount cb = new CBankAccount();

cb.Deposit(300);

cb.AddInterest();

cb.Withdraw(100);

We have used top level statements to write the main function.

An object of the class is created. Then the Deposit, AddInterest and Withdraw functions are called.


// output of the program 

Enter name of the bank: XYZ Bank
Amount deposited $300
Balance is $300
Thanks from XYZ Bank
=====================

Interest added $5
Balance is $305
Thanks from XYZ Bank
=====================

Withdrawl of $100
Balance is $205
Thanks from XYZ Bank
=====================

We can run the project to verify that we obtain the expected display. Thanks!


This Blog Post/Article "(C# Language) Practice Exercise in C# - static and const" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.