Interfaces basically define a blueprint for a class or a struct. The programmed definition of an interface looks very similar to a class, but nothing is implemented. Interfaces define the properties, methods, events, and indexers, but the interface does not define the implementation of any of these. It just declares their existence. Interfaces will not actually define any functionality. They just define ways in which interactions with a class takes place.
When to Use Interfaces
Interfaces allow us to create nice layouts for what a class is going to implement. Because of the guarantee the interface gives us, when many components use the same interface it allows us to easily interchange one component for another which is using the same interface. Dynamic programs begin to form easily from this.
Interfaces Overview
An interface has the following properties:
- • An interface is like an abstract base class: any non-abstract type inheriting the interface must implement all its members.
- • An interface cannot be instantiated directly.
- • Interfaces can contain events, indexers, methods and properties.
- • Interfaces contain no implementation of methods.
- • Classes and structs can inherit from more than one interface.
- • An interface can itself inherit from multiple interfaces.
Example: 1
Interface IHelloWorlder Definition
interface IHelloWorlder
{
void SayHello();
void SayGoodBye();
}
Implementing an Interface
public class MyHelloWorld : IHelloWorlder
{
public void SayHello()
{
Console.WriteLine("Hello world!");
}
public void SayGoodBye()
{
Console.WriteLine("Good Bye World!");
}
}
Example: 2
using System;
interface IParentInterface
{
void ParentInterfaceMethod();
}
interface IMyInterface : IParentInterface
{
void MethodToImplement();
}
class InterfaceImplementer : IMyInterface
{
static void Main()
{
InterfaceImplementer iImp = new InterfaceImplementer();
iImp.MethodToImplement();
iImp.ParentInterfaceMethod();
}
public void MethodToImplement()
{
Console.WriteLine("MethodToImplement() called.");
}
public void ParentInterfaceMethod()
{
Console.WriteLine("ParentInterfaceMethod() called.");
}
}
interface IParentInterface
{
void ParentInterfaceMethod();
}
interface IMyInterface : IParentInterface
{
void MethodToImplement();
}
class InterfaceImplementer : IMyInterface
{
static void Main()
{
InterfaceImplementer iImp = new InterfaceImplementer();
iImp.MethodToImplement();
iImp.ParentInterfaceMethod();
}
public void MethodToImplement()
{
Console.WriteLine("MethodToImplement() called.");
}
public void ParentInterfaceMethod()
{
Console.WriteLine("ParentInterfaceMethod() called.");
}
}
Above contains two interfaces: IMyInterface and the interface it inherits, IParentInterface. When one interface inherits another, any implementing classstruct must implement every interface member in the entire inheritance chain or
No comments:
Post a Comment