Defining Interfaces


Interfaces are defined with the interface keyword. Interfaces can have methods , properties, delegates, events, etc. However, each element contained in an interface must be the declaration of the element without any implementation.

To define an interface:

  1. Type public or internal depending on the scope you wish to give your interface.

  2. Type interface followed by a space.

  3. Type any name for the interface.

  4. Type { .

  5. Add the definitions for valid members ( Table 8.1 ).

  6. Type } ( Figure 8.5 ).

    Figure 8.5 The members of an interface are only definitions, with no code inside of them. Also, they don't have an access modifier in front; all the methods in the interface are public.
     public  interface  IHuman {     string Name { get; } //readonly property     void Eat(int Amount); //method     void Breathe(); //method } 
Table 8.1. Interface Members (Members that Can Be Added to an Interface Definition)

NAME

EXAMPLE

Method

string Method();

Property

int Age { get; set; }

Readonly Property

int Age { get; }

Indexer

long this[int index] {get; set;}

Event

event EventHandler OnClick;

graphics/tick.gif Tips

  • All interface methods are public by definition; you can't add an access modifier to the definition of the method (not even public).

  • Interface types can be used in the definition of parameters or variables ( Figure 8.6 ). However, interfaces are not creatable typesyou can't write new IAccount , for example.

    Figure 8.6 Once you define the interface you can use it as a data type either for variable declarations or parameter declarations.
     class DailyRoutine {    void Tasks()    {  IHuman man  ;  IHuman woman  ;    }    public void GoToDinner(  IHuman person  )    {      person->Eat();    } } 
  • Interfaces support method overloading ( Figure 8.7 ).

    Figure 8.7 Method overloading is the ability to have multiple methods with the same name. Remember that this can only be done if you change the number of parameters or change the type of one of the parameters.
     public interface IHuman {    string Name { get; }    //readonly property    void  Eat  (int Amount); //method    void  Eat  (string foodType, int Amount);    //overloading } 
  • Once other developers are using the interface, it's best not to change the interface definition; otherwise you risk having their programs stop working. Instead you should add a new interface definition, as you will see later in the section "Deriving One Interface from Another."




C#
C# & VB.NET Conversion Pocket Reference
ISBN: 0596003196
EAN: 2147483647
Year: 2003
Pages: 198
Authors: Jose Mojica

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net