Monday 6 January 2020

real time example of Interface in C#

we will discuss about interface in C# with real time example, it properties, implementations and pros and cons as well.
  1. An interface can never be instantiated e.g. ICar car = new ICar(); It’s wrong.
  2. It only contains signature of its methods.
  3. An interface has neither constructor nor fields.
  4. It is also not permitted to have access modifier on its methods.
  5. Its members are always implicitly public and cannot be declared as virtual or static.
We mostly asked interview for real time example of interface, so we will see it with a real example in this article. Take the example of Bank Account, there are many type of accounts, Saving Account, Current Account, Loan Account, Demat Account etc. so you know the features of these different accounts. In our example we will create saving account and current account from an interface IBankAccount to understand the feature of interface.
  1. We cannot withdraw more than a limit per day
  2. No limit for current account
So let’s create an interface IBankAccount with three methods Deposit, Withdraw and Balance.
  1. interface IBankAccount
  2. {
  3.     bool Deposit(decimal amount);
  4.     bool Withdraw(decimal amount);
  5.     decimal Balance { get; }
  6. }
Now we will create a new class SavingAccount inheriting from our IBankAccount interface
  1. public class SavingAccount : IBankAccount
  2. {
  3.     private decimal _balance;
  4.     private decimal _perDayLimit;
  5.     public bool Deposit(decimal amount)
  6.     {
  7.         _balance += amount;
  8.         return true;
  9.     }
  10.     public bool Withdraw(decimal amount)
  11.     {
  12.         if (_balance < amount)
  13.         {
  14.             Console.WriteLine("Insufficient balance!");
  15.             return false;
  16.         }
  17.         else if (_perDayLimit + amount > 5000) //limit is 5000
  18.         {
  19.             Console.WriteLine("Withdrawal attempt failed!");
  20.             return false;
  21.         }
  22.         else
  23.         {
  24.             _balance -= amount;
  25.             _perDayLimit += amount;
  26.       Console.WriteLine(String.Format("Successfully withdraw: {0,6:C}", amount));
  27.             return true;
  28.         }
  29.     }
  30.     public decimal Balance
  31.     {
  32.         get { return _balance; }
  33.     }
  34.     public override string ToString()
  35.     {
  36.         return String.Format("Saving Account Balance = {0,6:C}", _balance);
  37.     }
  38. }
Note the Withdraw method we check the day permission, while with current account there would not be any limit.
Here is our current account implementation
  1. public class CurrentAccount : IBankAccount
  2. {
  3.     private decimal _balance;
  4.     public bool Deposit(decimal amount)
  5.     {
  6.         _balance += amount;
  7.         return true;
  8.     }
  9.     public bool Withdraw(decimal amount)
  10.     {
  11.         if (_balance < amount)
  12.         {
  13.             Console.WriteLine("Insufficient balance!");
  14.             return false;
  15.         }
  16.         else
  17.         {
  18.             _balance -= amount;
  19.       Console.WriteLine(String.Format("Successfully withdraw: {0,6:C}", amount));
  20.             return true;
  21.         }
  22.     }
  23.     public decimal Balance
  24.     {
  25.         get { return _balance; }
  26.     }
  27.     public override string ToString()
  28.     {
  29.         return String.Format("Current Account Balance = {0,6:C}", _balance);
  30.     }
  31. }
As you can see here we are not checking the per withdrawal limit
Now we will write our Main method to test our interface and both the classes
  1. static void Main(string[] args)
  2. {
  3.     IBankAccount savingAccount = new SavingAccount();
  4.     IBankAccount currentAccount = new CurrentAccount();
  5.     savingAccount.Deposit(200);
  6.     savingAccount.Withdraw(100);
  7.     savingAccount.ToString();
  8.     currentAccount.Deposit(500);
  9.     currentAccount.Withdraw(600);
  10.     currentAccount.Withdraw(200);
  11.     currentAccount.ToString();
  12.     Console.ReadLine();
  13. }
And here is the output
Successfully withdraw : $100.00
Insufficient balance!
Successfully withdraw : $200.00
When we need an interface?
Suppose we have an event in our company for which we have different type of persons to register.
  1. Guest: with no fee but special treatment
  2. Employee: with no fee
  3. Outsiders: need to pay fee
Now we can create IPerson interface with a method Save and derive three classes Guest, Employee and Outsiders
  1. public interface IPerson
  2. {
  3.     int Save();
  4. }
  5. public class Guest : IPerson
  6. {
  7.     public String Name { get; set; }
  8.     ...............................
  9.     public int Save()
  10.     {
  11.         // Save as guest for the event
  12.         // Add Special treatment
  13.         return id;
  14.     }
  15. }
  16. public class Employee : IPerson
  17. {
  18.     public String Name { get; set; }
  19.     ...............................
  20.     public int Save()
  21.     {
  22.         // Save for the event
  23.         return id;
  24.     }
  25. }
  26. public class Outsiders : IPerson
  27. {
  28.     public String Name { get; set; }
  29.     ...............................
  30.     public int Save()
  31.     {
  32.         // Take the fee before saving it.
  33.         // Save outsider for event
  34.         return id;
  35.     }
  36. }
Let's create a list of different type of persons and I want to save all the person in my above list by using the Save method which should use the correct way to save, for guest no fee, special treatment, employee with no fee, outsiders with some fee.
  1. var personList = new List<IPerson>();
  2. personList.Add(new Guest { Name = "Guest 1" });
  3. personList.Add(new Employee { Name = "Employee 1" });
  4. personList.Add(new Outsiders { Name = "Outsider 1" });
  5. foreach(var person in personList)
  6. {
  7.     person.Save();
  8. }
Do you think, is that possible to pass different type of object as a list without the use of Interface or such clean code. Why I need to remember which type of person it is and then write the conditional code to save them with fee and other special treatment, create an interface, derive classes and call the save method on the interface and that will do all for us.

No comments:

Post a Comment

Baisic Useful Git Commands

  Pushing a fresh repository Create a fresh repository(Any cloud repository). Open terminal (for mac ) and command (windows) and type the be...