The interface keyword declares a reference type that has abstract members. The interface declaration takes the form:
[attributes] [modifiers] interface identifier [:base-list] {interface-body}[;]
where:
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. In the following example, the interface IMyInterface
inherits from two base interfaces, IBase1
and IBase2
:
interface IMyInterface: IBase1, IBase2 { void MethodA(); void MethodB(); }
Interfaces can be implemented by classes. The identifier of the implemented interface appears in the class base list. For example:
class Class1: Iface1, Iface2 { // class members }
When a class base list contains a base class and interfaces, the base class comes first in the list. For example:
class ClassA: BaseClass, Iface1, Iface2 { // class members }
For more information on interfaces, see §13 in the language reference.
For more information on properties and indexers, see Property Declaration and Indexer Declaration.
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 MyPoint
contains the property implementation.
// Interface implementation using System; interface IPoint { // Property signatures: int x { get; set; } int y { get; set; } } class MyPoint : IPoint { // Fields: private int myX; private int myY; // Constructor: public MyPoint(int x, int y) { myX = x; myY = y; } // Property implementation: public int x { get { return myX; } set { myX = value; } } public int y { get { return myY; } set { myY = value; } } } class MainClass { private static void PrintPoint(IPoint p) { Console.WriteLine("x={0}, y={1}", p.x, p.y); } public static void Main() { MyPoint p = new MyPoint(2,3); Console.Write("My Point: "); PrintPoint(p); } }
My Point: x=2, y=3
C# Keywords | Reference Types | Properties | Indexers | Grammar