98 out of 175 rated this helpful - Rate this topic

interface (C# Reference)

An interface contains only the signatures of methods, delegates or events. The implementation of the methods is done in the class that implements the interface, as shown in the following example:


      interface ISampleInterface
{
    void SampleMethod();
}

class ImplementationClass : ISampleInterface
{
    // Explicit interface member implementation: 
    void ISampleInterface.SampleMethod()
    {
        // Method implementation.
    }

    static void Main()
    {
        // Declare an interface instance.
        ISampleInterface obj = new ImplementationClass();

        // Call the member.
        obj.SampleMethod();
    }
}

An interface can be a member of a namespace or a class and can contain signatures of the following members:

An interface can inherit from one or more base interfaces.

When a base type list contains a base class and interfaces, the base class must come first in the list.

A class that implements an interface can explicitly implement members of that interface. An explicitly implemented member cannot be accessed through a class instance, but only through an instance of the interface, for example:

For more details and code examples on explicit interface implementation, see Explicit Interface Implementation (C# Programming Guide).

The following example demonstrates interface implementation. In this example, the interface IPoint contains the property declaration, which is responsible for setting and getting the values of the fields. The class Point contains the property implementation.

// keyword_interface_2.cs
// Interface implementation
using System;
interface IPoint
{
   // Property signatures:
   int x
   {
      get;
      set;
   }

   int y
   {
      get;
      set;
   }
}

class Point : IPoint
{
   // Fields:
   private int _x;
   private int _y;

   // Constructor:
   public Point(int x, int y)
   {
      _x = x;
      _y = y;
   }

   // Property implementation:
   public int x
   {
      get
      {
         return _x;
      }

      set
      {
         _x = value;
      }
   }

   public int y
   {
      get
      {
         return _y;
      }
      set
      {
         _y = value;
      }
   }
}

class MainClass
{
   static void PrintPoint(IPoint p)
   {
      Console.WriteLine("x={0}, y={1}", p.x, p.y);
   }

   static void Main()
   {
      Point p = new Point(2, 3);
      Console.Write("My Point: ");
      PrintPoint(p);
   }
}

Output

 
My Point: x=2, y=3

For more information, see the following sections in the C# Language Specification:

  • 1.9 Interfaces

  • 3.4.5 Interface members

  • 4.2.4 Interface types

  • 10.1.2.2 Interface implementations

  • 11.2 Struct interfaces

  • 13 Interfaces

Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Properties and indexers can also be interface members
This page isn't accurate. It starts by stating "An interface contains only the signatures of methods, delegates or events." and that is just NOT TRUE. Please correct the opening text to
"An interface contains only the signatures of methods, properties, events or indexers." to match the VS2010 page.
Difference between abstract and interface?
What is the difference between abstract and interface?

Answer:
Classes may only derive from one base class, but can derive from multiple interfaces. An abstract class is useful because it can contain member variables and other things that interfaces can't. But if you need to derive from two "classes," at least one of them will need to be an interface.
Question...
I've been trying to truly understand the use of interfaces, but to be honest I haven't figured it out yet. What's the difference, in the above example of using:

static void PrintPoint(IPoint p)
Instead of

static void PrintPoint(Point p)

Why would I want to use one and not the other? What's the point of having the interface if I have to create an instance of my Point class anyway?

Answer(Noonan):
For background information, Interfaces are often used when developing an API so that you don't have to change the method signatures that others will be programming against.
In answer to your question, by requiring a parameter of IPoint instead of Point you allow any object that implements IPoint to be passed in. Whereas requiring a Point parameter means the object must be of type Point or a subclass of Point.
The IPoint parameter gives programmers calling this method far greater flexibility as a class can implement multiple interfaces and need not be related in the class heirarchy, but a class can only inheret from one other class.
Say for example you had a class, Battleship that describes a battleship, including it's position on screen. This class could conceivably implement IPoint to describe it's position, but inherit from a Ship class. You could then pass an instance of Battleship to the PrintPoint( IPoint p ) method and the Battleship's position will be printed. This would not be possible with the PrintPoint( Point p ) version, as it would make no sense for the Battleship class to inherit from the Point class.
So even though Battleship and Point classes are not related in the class heirarchy, you could still pass a Battleship to PrintPoint( IPoint p ) if Battleship implements IPoint.

Interfaces Implicitas vs Explicitas

Referencia: http://caminoalmcpd.blogspot.com/2010/10/interfaces-implicitas-vs-explicitas.html

Basicamente la diferencia principal entre los dos tipos de implementacion es que cuando se hace de forma implicita es posible acceder a los métodos mediante una instancia de la clase pero cuando se hace de forma explicita solo se puede acceder al método mediante una instancia de la interfaz. En el siguiente ejemplo vemos como se debe llamar al método dependiendo del tipo de implementación que se hizo:

// Llamado Implicito
MiClaseImplicita oImplicita = new MiClaseImplicita( );
oImplicita.Metodo( );

// Llamado Explicito
IMiInterfaz oExplicita = new MiClaseExplicita( );
oExplicita.Metodo( );

Al implementar una interfaz de manera explicita debemos tener en cuenta lo siguiente:

Las clases que implementan interfaces de manera explicita no pueden ser abstractas.
Las clases derivadas de clases que implementan interfaces de manera explícita no pueden sobrescribir los métodos definidos explícitamente

Interface Instances

I've been doing a lot of reading on Interfaces but there's still one thing that puzzles me. If we can't instantiate an Interface, then what does this do:

ISampleInterface obj = new ImplementationClass();

Answer: (Noonan)
In the above line of code an object of type ImplementationClass is created with

new ImplementationClass( );

This is then assigned to a variable named 'obj'. This 'obj' variable is of type ISampleInterface (which is an interface type).

This assignment is possible because ImplementationClass implements the ISampleInterface interface. In fact any object created from any class that implements ISampleInterface could be assigned to 'obj' in this example.
By doing this you have not instantiated the interface (as you mentioned, that is not possible). Rather you have simply assigned an object of type ImplementationClass to a variable of type ISampleInterface.

By analogy, you could also assign the ImplementationClass object in this example to a variable that has the type of a base class of ImplementationClass. However, this is not strictly the same, since this is based on inheritance , whereas interfaces are implemented and are not strictly part of the class hierarchy.
For example you could also do,

Object object1 = new ImplementationClass();  // Assuming ImplementationClass derives from Object

The object1 variable is of type Object, not of type ImplementationClass, although the object assigned to it is of type ImplementationClass. This is similar for Interface variable types, noting the differences between inheritance and implementation. Eg. a class can implement many interfaces but can only inherit from one immediate parent.

WHY?

Don't you find quite confusing when you do this:

interface IThing {
    void Do();
}

class Thing: IThing {
  public void Do() {
     Console.WriteLine("Do the Thing");
   }
  void IThing.Do() {
    Console.WriteLine("IThing is INTERFACE!!");
   }
}
void Main() {
  IThing t = new Thing();
  t.Do();
}

And it displays : IThing is INTERFACE!!
How come you create instance of Thing object and it box it to IThing level, in point of view of Interface it should have a pointer on original object and trigger "Do the Thing".

Answer: (Noonan)
IThing.Do() takes precedence over Do() method since this is Explicit Interface Implementation see http://msdn.microsoft.com/en-us/library/ms173157.aspx

Edit: (Noonan)
NB: I reposted this using IE because, I'm guessing trbothead you used Chrome or something (like I did originally) to post and it garbled the line ends and code formatting.

Use of Interfaces
To use an example my Object Oriented Programming teacher showed us:

Lets say we make an IRaceable interface that has a Speed property.

You can have a RaceCar that inherits the IRaceable interface.
You can also have a Dog that inherits the IRaceable interface.

You can then use a method that uses IRaceable and, since both Dog and RaceCar have the interface and thus both have a speed property, you can be sure that you can use Speed whenever you reference IRaceable things.
The difference between Point and IPoint
The difference between the two declarations is that 'IPoint p' will accept any object that implements the IPoint interface, however 'Point p' will only accept objects of class type Point. In the example, the usage of Point and IPoint are interchangeable.