C Sharp

Declaring Interfaces

Interfaces can contain methods, properties, indexers, and events-none of which are implemented in the interface itself. Let's look at an example to see how to use this feature. Suppose you're designing an editor for your company that hosts different Windows controls. You're writing the editor and the routines that validate the controls users place on the editor's form. The rest of the team is writing the controls that the forms will host. You almost certainly need to provide some sort of form-level validation. At appropriate times-such as when the user explicitly tells the form to validate all controls or during form processing-the form could then iterate through all its attached controls and validate each control, or more appropriately, tell the control to validate itself.

How would you provide this control validation capability? This is where interfaces excel. Here's a simple interface example containing a single method named Validate: -

interface IValidate
{
    bool Validate();
}

Now you can document the fact that if the control implements the IValidate interface, the control can be validated.

Let's examine a couple of aspects of the preceding code snippet. First, you don't need to specify an access modifier such as public on an interface method. In fact, prepending the method declaration with an access modifier results in a compile-time error. This is because all interface methods are public by definition. (C++ developers might also notice that because interfaces, by definition, are abstract classes, you do not need to explicitly declare the method as being pure virtual by appending = 0 to the method declaration.) -

In addition to methods, interfaces can define properties, indexers, and events, as shown here: -

interface IExampleInterface
{
    // Example property declaration.
    int testProperty { get; }
    // Example event declaration.
    event testEvent Changed;
    // Example indexer declaration.
    string this[int index] { get; set; }
}