You are currently viewing What is Interface in C# and how to use them?

What is Interface in C# and how to use them?

An interface is a contract contains methods, properties, events and indexers. A class or structure that implements the interface must implement all the members of the interface. The interface defines ‘what’ part of the contract and classes or structure that implements the interface defines ‘how’ part of the contract.

 

Methods, properties, events are the members of the interface. Interface contains only the declaration of the members. The responsibility of derive class or structure to define all members specified in interface definition.

.Net does not support multiple inheritance, but one can achieve this objective by implementing multiple interfaces to class. In short, interface is an agreement or contract that is forced a developer to implement all the declaration and define them in class or structure.

 

How to declare, implement and use Interfaces

interface IBankAccount
{
string Name { get; set; }
double Deposit { get; set; }
double Withdraw { get; set; }
double CalculateBalance();
}

interface IBankAccount
{
string Name { get; set; }
double Deposit { get; set; }
double Withdraw { get; set; }
double CalculateBalance();
}

public class SavingAccount : IBankAccount
{
// Implementing interface.
public string Name { get; set; }
public double Deposit { get; set; }
public double Withdraw { get; set; }
public double CalculateBalance()
{
return Deposit - Withdraw;
}
}

public class CurrentAccount : IBankAccount
{
// Implementing interface.
public string Name { get; set; }
public double Deposit { get; set; }
public double Withdraw { get; set; }
public double CalculateBalance()
{
return Deposit - Withdraw;
}
}

class Program
{
static void Main(string[] args)
{
IBankAccount savingAccount = new SavingAccount();
savingAccount.Name = "You";
savingAccount.Deposit = 50000;
savingAccount.Withdraw = 15000;
IBankAccount currentAccount = new CurrentAccount();
currentAccount.Name = "You";
currentAccount.Deposit = 80000;
currentAccount.Withdraw = 20000;
Console.WriteLine("==== Saving Account ====");
Console.WriteLine(" {0} have deposited {1}.", savingAccount.Name, savingAccount.Deposit);
Console.WriteLine(" {0} have withdraw {1}.", savingAccount.Name, savingAccount.Withdraw);
Console.WriteLine(" {0} have {1} balance in your account.", savingAccount.Name, savingAccount.CalculateBalance());
Console.WriteLine("==== Current Account ====");
Console.WriteLine(" {0} have deposited {1}.", currentAccount.Name, currentAccount.Deposit);
Console.WriteLine(" {0} have withdraw{1}.", currentAccount.Name, currentAccount.Withdraw);
Console.WriteLine(" {0} have {1} balance in your account.", currentAccount.Name, currentAccount.CalculateBalance());
Console.ReadLine();
}
}

Output: interface-output

 

Leave a Reply