O'Reilly logo

C# 3.0 Pocket Reference, 2nd Edition by Ben Albahari, Joseph Albahari

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Interfaces

An interface is similar to a class, but it provides a specification rather than an implementation for its members. An interface is special in the following ways:

  • A class can implement multiple interfaces. In contrast, a class can inherit from only a single class.

  • Interface members are all implicitly abstract. In contrast, a class can provide both abstract members and concrete members with implementations.

  • Structs can implement interfaces. In contrast, a struct cannot inherit from a class.

An interface declaration is like a class declaration, but it provides no implementation for its members, as all its members are implicitly abstract. These members will be implemented by the classes and structs that implement the interface. An interface can contain only methods, properties, events, and indexers, which noncoincidentally are precisely the members of a class that can be abstract.

Here is a slightly simplified version of the IEnumerator interface, defined in System.Collections:

	public interface IEnumerator
	{
	  bool MoveNext();
	  object Current {get;}
	}

Interface members have the same accessibility as the interface type, and they cannot declare an access modifier.

Implementing an interface means providing a public implementation for all its members:

	internal class Countdown : IEnumerator
	{
	  int count = 11;
	  public bool MoveNext()  { return count-- > 0 ;   }
	  public object Current   { get { return count; }  }
	}

You can implicitly cast an object to any interface that it implements. For example: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required