Lesson13 PDF
Lesson13 PDF
LESSON 13 - INTERFACES
B E G I N N E R S ’ S
C# TUTORIAL
1 3 . I N T E R F A C E S
WWW.CSHARP–STATION.COM
PAGE 1 OF 4
COPYRIGHT © 2000–2003 C# STATION , ALL RIGHTS RESERVED
BEGINNERS C# TUTORIAL
LESSON 13 - INTERFACES
An interface looks like a class, but has no implementation. The only thing it
contains are definitions of events, indexers, methods and/or
properties. The reason interfaces only provide definitions is because they
are inherited by classes and structs, which must provide an implementation
for each interface member defined.
interface IMyInterface
{
void MethodToImplement();
}
PAGE 2 OF 4
COPYRIGHT © 2000–2003 C# STATION , ALL RIGHTS RESERVED
BEGINNERS C# TUTORIAL
LESSON 13 - INTERFACES
Now that this class inherits the IMyInterface interface, it must implement
its members. It does this by implementing the MethodToImplement()
method. Notice that this method implementation has the exact same
signature, parameters and method name, as defined in the IMyInterface
interface. Any difference will cause a compiler error. Interfaces may also
inherit other interfaces. Listing 13-3 shows how inherited interfaces are
implemented.
using System;
interface IParentInterface
{
void ParentInterfaceMethod();
}
PAGE 3 OF 4
COPYRIGHT © 2000–2003 C# STATION , ALL RIGHTS RESERVED
BEGINNERS C# TUTORIAL
LESSON 13 - INTERFACES
The code in listing 31.3 contains two interfaces: IMyInterface and the
interface it inherits, IParentInterface. When one interface inherits another,
any implementing class or struct must implement every interface member
in the entire inheritance chain. Since the InterfaceImplementer class in
Listing 13-3 inherits from IMyInterface, it also inherits
IParentInterface. Therefore, the InterfaceImplementer class must
implement the MethodToImplement() method specified in the IMyInterface
interface and the ParentInterfaceMethod() method specified in the
IParentInterface interface.
In summary, you now understand what interfaces are. You can implement
an interface and use it in a class. Inherfaces may also be inherited by other
interface. Any class or struct that inherits an interface must also
implement all members in the entire interface inheritance chain.
PAGE 4 OF 4
COPYRIGHT © 2000–2003 C# STATION , ALL RIGHTS RESERVED