Sunday, April 3, 2016

Use Of Interface with Example...


Interface is very important concept in C#. The usual answer we get for Why to use Interface is - "To achieve Multiple Inheritance which is not directly supported by C#." This seems to me partially true because we don't have method definition in interface unlike in  class implementing multiple inheritance. Also we can have properties but we do not have variable declaration in interface.

Again the same question then: What is the use of interface?

Microsoft says there are several other reasons why one should use interfaces instead of class inheritance:
  • Interfaces are better suited to situations in which your applications require many possibly unrelated object types to provide certain functionality.
  • Interfaces are more flexible than base classes because you can define a single implementation that can implement multiple interfaces.
  • Interfaces are better in situations in which you do not have to inherit implementation from a base class.
  • Interfaces are useful when you cannot use class inheritance. For example, structures cannot inherit from classes, but they can implement interfaces.
Lets try to understand this with below example:

 



You got something!! Consider a scenario of any bank where you want to check name of the customers associated with the bank.  Bank will not give you all the details like one's account number or account balance. Practically with an object of each account (class in this e.g.) user can access anything which bank certainly don't want to but just account name is something which is not confidential and associated with each account. 


See how we are displaying the customer name - we are adding the object (Account Key) of each customer to array list so that we can iterate through their respective class methods and then passing it to the DisplayCustomers() method. Now we are referring each customer object to the Interface object in foreach. WHY?? WHY?? WHY?? Why the bloody hell we are not directly accessing through respective Class object now?? Because accessing interface provides an upper level security to the class methods. It will only allow us to access myaccountName() method which is declared inside ISbiAccountName intreface and implemented by multiple classes.





 

Output:



There is one more concept called "Implement interface explicitly". 

Consider two person having same name leaving together. How you gonna call them. I guess with some identity - may be adding father's name which is unique. Now, below example it self is explanatory - 



 Comment down below if you have any queries. Happy Learning :)