I cannot get my head around how to use interfaces and why they are needed. Can someone please show me a simple example?
-
8Plug "interface" into the search box. There are some excellent question/answer threads already on SO. For example: http://stackoverflow.com/questions/444245/how-will-i-know-when-to-create-an-interface – AJ. Nov 12 '10 at 16:59
-
2There are dozens of questions on interfaces, including a handful of "what are they and why/how to use them" question. Also, Google. (Edit: Now -1. I wouldn't necessarily downvote, but this question doesn't deserve upvotes either imo) – Nov 12 '10 at 16:59
9 Answers
interface IFlyable
{
void Fly();
}
class Bird : IFlyable
{
public void Fly() { }
}
class Plane : IFlyable
{
public void Fly() { }
}
List<IFlyable> things = GetBirdInstancesAndPlaneInstancesMixed();
foreach(IFlyable item in things)
{
item.Fly();
}
Bird
and Plane
have no common base class except Object
, but you can see using the same interface we can deal with them grouply in our program, because they have the same "feature": Fly.

- 42,509
- 16
- 113
- 174
-
1
-
What difference if you right: `class IFlyable`? What need for interface? – Alireza Zojaji May 01 '17 at 00:54
-
2@AmirZojaji Because `Plane` probably already has a base class like `Machine`, and `Bird` has its base class `Animal`. Interfaces are easy to be combined, unlike base classes. – Cheng Chen Aug 15 '17 at 01:42
-
-
@Bigeyes The access modifier "public" is not allowed in interfaces, you can have a try. – Cheng Chen Apr 23 '19 at 02:34
-
@ChengChen, but the answer below has `public` such as `public interface ISpeaks` – Bigeyes Apr 23 '19 at 21:20
-
1@Bigeyes `public interface IFoo` is allowed, while putting `public` before the methods of the interface is not. Here in my answer, it doesn't matter if `IFlyable` is public or not. – Cheng Chen Apr 24 '19 at 02:36
public interface ISpeaks
{
string Speak();
}
public class Dog : Mammal, ISpeaks
{
public string Speak() { return "Woof!"; }
}
public class Person : Mammal, ISpeaks
{
public string Speak() { return "Hi!"; }
}
//Notice Telephone has a different abstract class
public class Telephone : Appliance, ISpeaks
{
public Person P { get; set; }
public Telephone(Person p)
{
P = p;
}
public string Speak() { return P.Speak(); }
}
[Test]
public void Test_Objects_Can_Speak()
{
List<ISpeaks> thingsThatCanSpeak = new List<ISpeaks>();
//We can add anything that implements the interface to the list
thingsThatCanSpeak.Add(new Dog());
thingsThatCanSpeak.Add(new Person());
thingsThatCanSpeak.Add(new Telephone(new Person()));
foreach(var thing in thingsThatCanSpeak)
{
//We know at compile time that everything in the collection can speak
Console.WriteLine(thing.Speak());
}
}
This is useful because we can code against the interface rather than implementation and because we can use multiple interfaces on a single class, we are more flexible than if we used an Abstract class.

- 29
- 8

- 35,279
- 21
- 87
- 141
-
Except your `thingsThatCanSpeak.Add(new Telephone());` wont work because Telephone requires a Person in the constructor ;) – Nate Nov 12 '10 at 17:10
-
+1 for showing the abstract bit, interfaces define something the inheriting classes should do, not what inheriting classes should be. – Paul Hadfield Nov 12 '10 at 18:51
-
@Nate Thanks for that, added it later to illustrate the abstract class difference. – Rob Stevenson-Leggett Nov 12 '10 at 18:55
Interfaces
are somehow class definition alike, a sort of contract between the interface
and the class implementing it.
An interface contains only the signatures of methods, properties, events or indexers. A class or struct that implements the interface must implement the members of the interface that are specified in the interface definition.
A .NET class cannot use multi-inheritance. As such, we rely on interfaces, and a class can implement as much interfaces as you wish. On the contrary, a class inheritance has to be single. For instance:
public class Customer : Person, Company {
}
This code is not allowed in any .NET languages that I know (C#/VB.NET).
To counter this lack, if we may say so, we rely on interfaces.
public interface IPerson {
string Name
string Address
string StateProvince
string ZipPostalCode
string Country
long PhoneNumber
}
public interface ICompany {
string CreditTerm
string BillingAddress
string ShippingAddress
string ContactName
long ContactPhoneNumber
long FaxNumber
}
public class Customer : IPerson, ICompany {
// Properties implementations here.
}
In this way, interfaces are like a workaround somehow to multi-inheritance.
On the other hand, interfaces can be used as a contract for methods. Let's say you got a method that take an ICompany
as an input parameter. You are now sure to have the properties defined in the ICompany
interface to perform your work within the method.
public BillCompany(ICompany company) {
// Bill company here...
}
Then, your Customer
class correspond to what you are expecting, since it implements the ICompany
interface.
Let's make another class, whose definition would only implement the IPerson
interface.
public class Individual : IPerson {
// Interface implementation here...
}
Then, your BillCompany()
method could not accept an instance of the Individual
class, as it doesn't show requirements (properties, etc.) for a company.
In short, interfaces are a good way to bind by contract your methods to what will be accepted, like inheritance.
There are indeed some precautions to take while working with Interface
s, a change to an interface will break your code, as an enforcing rule to implement the new member within all implementing classes, which class inheritance does not.
Does this help?

- 23,773
- 22
- 96
- 162
-
based on [msdn](https://msdn.microsoft.com/en-us/library/ms173156.aspx) An interface can't contain **constants**, **fields**, **operators**, **instance constructors**, **destructors**, or **types**. please edit your answer – ako Aug 09 '16 at 22:46
I like this blog post that I read the other day: http://simpleprogrammer.com/2010/11/02/back-to-basics-what-is-an-interface/
Many people, myself included, have created interfaces that have a 1 to 1 mapping to the class they are representing but this is not always a good thing and that article explains why.

- 6,088
- 2
- 35
- 56
An interface is useful when you have a given contract you want an object to fulfill but you don't really care about how they fulfill it. That's an implementation detail left to the class itself.
So let's say you have a method that's job is to process save requests. It does not perform the actual act of saving, it just processes the requests. As a result, it can take a List<ICanSave>
, where ICanSave
is an interface. The objects in that list can be any type that implements that interface. It can be a mix, or it can contain just one type. You're just concerned that it implements the interface.
public interface ICanSave
{
void Save();
}
In your method, you might have something simple like
public void SaveItems(List<ICanSave> items)
{
foreach (var item in items)
{
item.Save();
}
}
How are those items being saved? You don't care! That, again, is an implementation detail for the class implementing the interface. You just want whatever class that enters the method to have that ability.
You could have a class that implements the interface that persists data to the file system. Another might save to a database. Another may call some external service. Etc. That's left for the author of the class to decide. You might even have a stubbed class for a unit test that does nothing at all.
That's just one use-case scenario, there are many others, several in the BCL. IEnumerable<T>
is a good one, it is implemented by things such as ICollection<T>
and IList<T>
, which are in turn implemented by concrete types such as Array
and List<T>
. It's the interface which makes many of the programming constructs you may be accustomed to useful, such as LINQ. LINQ doesn't care about the actual implementation* of the class, it just wants to be able to enumerate it and perform the proper filtering and/or projection.
IDisposable
is another good BCL example. You want to know that a class needs to clean up after itself. What specifically it needs to clean up is left up to the class, but by nature of it implementing IDisposable
, you know it needs to clean up after itself, so you preferrably wrap its use in a using
statement or you manually ensure that you call .Dispose
once you've finished working with the object.
*LINQ actually does optimize for some interfaces.

- 123,721
- 27
- 225
- 246
Simple example of interface Animal with two implementation of class animal (you have an unique description for animal and many implementation in class dog, cat...)
public interface IAnimal
{
string GetDescription();
}
class Cat : IAnimal
{
public string GetDescription()
{
return "I'm a cat";
}
}
class Program
{
static void Main(string[] args)
{
Cat myCat = new Cat();
Console.WriteLine(myCat.GetDescription());
}
}

- 503
- 3
- 9
Here is the main points of Interface,
1.We can call same method using different classes with different out put of same methods.
Simple Example:
class Mango : abc
{
public static void Main()
{
System.Console.WriteLine("Hello Interfaces");
Mango refDemo = new Mango();
refDemo.mymethod();
Orange refSample = new Orange();
refSample.mymethod();
}
public void mymethod()
{
System.Console.WriteLine("In Mango : mymethod");
}
}
interface abc
{
void mymethod();
}
class Orange : abc
{
public void mymethod()
{
System.Console.WriteLine("In Orange : mymethod");
}
}
2.can call same method using same interface with different classes.
class Mango : abc
{
public static void Main()
{
System.Console.WriteLine("Hello Interfaces");
abc refabc = new Mango();
refabc.mymethod();
abc refabd = new Orange();
refabd.mymethod();
Console.ReadLine();
}
public void mymethod()
{
System.Console.WriteLine("In Mango : mymethod");
}
}
interface abc
{
void mymethod();
}
class Orange : abc
{
public void mymethod()
{
System.Console.WriteLine("In Orange : mymethod");
}
}

- 1
- 1

- 639
- 7
- 11
"I've got a bunch of classes here that I want to treat the same way, for a certain amount of functionality."
So, you write a contract.
Real-world example: I'm writing a wizard. It has a bunch of pages, some of which (but not all) are UserControls. They all need a common set of operations, so the controlling class can treat them all the same. So I have an IPage interface that they all implement, with operations like initializing the page, saving the user's choices, et cetera. In my controller, I simply have a List, and don't have to know what page does what; I simply call the interface's Save()s and Initialize()s.

- 15,675
- 4
- 43
- 74
Well from MSDN, "An interface defines a contract. A class or struct that implements an interface must adhere to its contract."
On this page, there are several examples of what an interface looks like, how a class inherits from an interface and a full blown example of how to implement an interface.
Hope this helps out some.

- 6,272
- 9
- 35
- 57