An interface is a .NET reference type that specifies the public members of a type. They are inherited, and any type that inherits an interface must implement the members specified in the interface. Another way to view an interface is that it specifies a contract, in which any type implementing that interface promises to implement its members. The benefits of interfaces include ease of development and maintenance and more robust code. Because an interface is something that may be used commonly across many classes, interfaces are easily identifiable. For example, a type that implements IDisposable has a Dispose method, which supports the Dispose pattern for unmanaged resource collection. Another example is the IEnumerable interface, which is used by the foreach statement to iterate through arrays and collections. Additionally, code with interfaces is more robust because the C# compiler ensures that every member of an inherited interface is implemented. Listing 4.8 shows the syntax of implementing an interface. Listing 4.8 Interface Syntax (InterfaceSyntax.cs)using System; // interface to inherit and implement public interface MyInterface { event EventHandler MyEvent; void MyMethod(); int this[int index] { get; set; } int MyProperty { get; set; } } // type inheriting interface public class MyClass : MyInterface { public event EventHandler MyEvent; public void MyMethod() { // some method implementation } public int this[int index] { get { return 0; } set { // some set accessor implementation } } public int MyProperty { get { return 0; } set { // some set accessor implementation } } } class InterfaceSyntax { static void Main() { } } The interface MyInterface in Listing 4.8 shows how to declare each type member. Notice that fields are not present because interfaces can't specify them. MyClass implements MyInterface by specifying an inheritance relationship in the declaration. Classes and structs can implement multiple interfaces by separating each with a comma in their declaration. Because MyClass inherits MyInterface, the C# compiler forces it to implement each MyInterface member.
|