-
Aug 29th, 2009, 09:55 AM
#1
Thread Starter
Member
Interface
I Know the usage of Interfaces. What is the real life usage ?
-
Aug 30th, 2009, 10:04 AM
#2
Re: Interface
Are you asking for examples? If so:
csharp Code:
foreach (var item in myList)
myList must implement IEnumerable in order to be used in a 'foreach' loop.
csharp Code:
using (var obj = new SomeType())
SomeType must implement IDisposable to be used in a 'using' statement. In order to assign an object to the DataSource of a DataGridView, ComboBox or ListBox that object must implement the IList or IListSource interface. In order to be added to the WinForms designer Toolbox a type must implement the IComponent interface. Etc., etc.
-
Nov 24th, 2009, 01:53 AM
#3
Thread Starter
Member
Re: Interface
Thanks for the reply jmc.
Where do we really need to use interface. I was asked this in a interview
-
Nov 24th, 2009, 03:35 AM
#4
Re: Interface
I've already shown you two examples of where we need to use interfaces. Are you actually asking where we need to implement interfaces in our own classes? Where we need to define our on interfaces? Something else?
One example of where you might define and implement your own interface is for the sake of unit testing. I'm currently working on an ASP.NET MVC project with views, controllers, a service layer, a repository and a data access layer. Both the service layer and the repository are defined as interfaces that are then implemented in classes. The interfaces allow you to create mock implementations of the repository to facilitate unit testing the service layer and mock implementations of the service layer to facilitate unit testing the controllers.
Another example of where an interface might be used is for an app that supports plug-ins. An interface is declared to define the functionality a plug-in must provide, then numerous classes can implement it and be plugged into the app.
-
Nov 24th, 2009, 09:09 AM
#5
Addicted Member
Re: Interface
Yeah plug-ins, extensibility,testing. Also a big one is the Strategy Pattern. Using a Strategy pattern on a switch statement.
I've read that it's best to program to abstract classes or interfaces as it's good SOLID programming practice.
When you write to an interface you don't depend on that implementation of the class you are utilizing. Then if that class is unavailable to you to make changes to, you need to write a class that the code you have already written would accept, without having to change much of your existing code. The new class that implements the common interface could just slide right in.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|