Interface in C# with real time example

Interface in C# with real time example why we need interface? when we need interface interface usage pros & cons how to improve your code with interface? C# interface usage

In this article 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.

interface IBankAccount
{
    bool Deposit(decimal amount);
    bool Withdraw(decimal amount);
    decimal Balance { get; }
}

Now we will create a new class SavingAccount inheriting from our IBankAccount interface

public class SavingAccount : IBankAccount
{
    private decimal _balance;
    private decimal _perDayLimit;
    public bool Deposit(decimal amount)
    {
        _balance += amount;
        return true;
    }
    public bool Withdraw(decimal amount)
    {
        if (_balance < amount)
        {
            Console.WriteLine("Insufficient balance!");
            return false;
        }
        else if (_perDayLimit + amount > 5000) //limit is 5000
        {
            Console.WriteLine("Withdrawal attempt failed!");
            return false;
        }
        else
        {
            _balance -= amount;
            _perDayLimit += amount;
      Console.WriteLine(String.Format("Successfully withdraw: {0,6:C}", amount));

            return true;
        }
    }
    public decimal Balance
    {
        get { return _balance; }
    }

    public override string ToString()
    {
        return String.Format("Saving Account Balance = {0,6:C}", _balance);
    }
}

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

public class CurrentAccount : IBankAccount
{
    private decimal _balance;
    public bool Deposit(decimal amount)
    {
        _balance += amount;
        return true;
    }
    public bool Withdraw(decimal amount)
    {
        if (_balance < amount)
        {
            Console.WriteLine("Insufficient balance!");
            return false;
        }
        else
        {
            _balance -= amount;
      Console.WriteLine(String.Format("Successfully withdraw: {0,6:C}", amount));

            return true;
        }
    }
    public decimal Balance
    {
        get { return _balance; }
    }

    public override string ToString()
    {
        return String.Format("Current Account Balance = {0,6:C}", _balance);
    }
}

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

static void Main(string[] args)
{
    IBankAccount savingAccount = new SavingAccount();
    IBankAccount currentAccount = new CurrentAccount();

    savingAccount.Deposit(200);
    savingAccount.Withdraw(100);
    savingAccount.ToString();

    currentAccount.Deposit(500);
    currentAccount.Withdraw(600);
    currentAccount.Withdraw(200);
    currentAccount.ToString();

    Console.ReadLine();
}

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

public interface IPerson 
{
    int Save();
}
public class Guest : IPerson
{
    public String Name { get; set; }
    ...............................
    public int Save()
    {
        // Save as guest for the event
        // Add Special treatment
        return id;
    }
}

public class Employee : IPerson
{
    public String Name { get; set; }
    ...............................
    public int Save()
    {
        // Save for the event
        return id;
    }
}

public class Outsiders : IPerson
{
    public String Name { get; set; }
    ...............................
    public int Save()
    {
        // Take the fee before saving it.
        // Save outsider for event

        return id;
    }
}

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.

var personList = new List<IPerson>();
personList.Add(new Guest { Name = "Guest 1" });
personList.Add(new Employee { Name = "Employee 1" });
personList.Add(new Outsiders { Name = "Outsider 1" });

foreach(var person in personList)
{
    person.Save();
}

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.

I tried my best to explain it and if it can help anyone, otherwise whatever you will write, you cannot make every one happy. So if you have any better example please share with us.

Ali Adravi Having 13+ years of experience in Microsoft Technologies (C#, ASP.Net, MVC and SQL Server). Worked with Metaoption LLC, for more than 9 years and still with the same company. Always ready to learn new technologies and tricks.
  • interface
  • c#
  • oops
By Ali Adravi On 18 Aug, 13  Viewed: 47,535

Other blogs you may like

default value for different data type in C#

In C# there are different data type and they use some default value when we declare a variable. When we define a variable of type int or Int32 say int score; so what is the value of score, will it be null or zero, in the same way if we create a variable of type string/String what value it holds... By Ali Adravi   On 27 Mar 2013  Viewed: 2,599

enum in C# and conversion

An enumeration type (also known an enumeration or an enum) provides an efficient way to define a set of named integral constants that may be assigned to a variable to make programming clear, understandable and manageable. There are ways of using, like how to use enum in switch and case statement,... By Hamden   On 27 Mar 2013  Viewed: 4,525

Dynamic vs var in C# with example

When we have var which dynamically holds any type or value so why we need dynamic type, what are the differences and situations where we can use dynamic rather than var, there were some question in my mind so I explored more which I want to share here. There are two things, static type and... By Nathan Armour   On 26 Mar 2013  Viewed: 3,204

Array in C# - single, multiple and jagged array

An array can be initialized in several ways, it can store a single value or series of values, every element must be set of same type, C# supports single-dimensional arrays, multidimensional arrays (also call rectangular array) and array-of-arrays (referred jagged arrays), let’s discuss features of... By Ali Adravi   On 24 Mar 2013  Viewed: 4,336

XmlDocument Vs XDocument and their usage

When there was XmlDocument why we need XDocument, is there any better feature available with XDocument, answer is yes, XDocument has a number of benefits, easy to create, easy to update, easy to search, ability to use LINQ to XML, cleaner object model etc. In this post we will see some examples... By Ali Adravi   On 16 Mar 2013  Viewed: 3,482