This post was most recently updated on August 5th, 2024
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 Interfaces?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
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: