Interface
An Interface in [Computer science] refers to a set of named operations that can be invoked by clients. Interface generally refers to an abstraction that an entity provides of itself to the outside. This separates the methods of external communication from internal operation (for example two different functions written in C language have the same interface if they have the same arrangements of arguments and the same type of return value, but the function body may be implemented in different way), and allows it to be internally modified without affecting the way outside entities interact with it, as well as provide multiple abstractions of itself. It may also provide a means of translation between entities which do not speak the same language, such as between a human and a computer. Because interfaces are a form of indirection, some additional overhead is incurred versus direct communication.
The interface of a software module A is deliberately kept separate from the implementation of that module. The latter contains the actual code of the procedures and methods described in the interface, as well as other "private" variables, procedures, etc.. Any other software module B (which can be referred to as a client to A) that interacts with A is forced to do so only through the interface. One practical advantage of this arrangement is that replacing the implementation of A by another one that meets the same specifications of the interface should not cause B to fail—as long as its use of A complies with the specifications of the interface
// Assembly: Common Classes
namespace CommonClasses
{
public interface IAnimal
{
string Name { get; }
string Talk();
}
}
// Assembly: Animals
using System;
using CommonClasses;
namespace Animals
{
public abstract class AnimalBase
{
public string Name { get; private set; }
protected AnimalBase(string name) {
Name = name;
}
}
public class Cat : AnimalBase, IAnimal
{
public Cat(string name) : base(name) {
}
public string Talk() {
return "Meowww!";
}
}
public class Dog : AnimalBase, IAnimal
{
public Dog(string name) : base(name) {
}
public string Talk() {
return "Arf! Arf!";
}
}
}
// Assembly: Program
// References and Uses Assemblies: Common Classes, Animals
using System;
using System.Collections.Generic;
using Animals;
using CommonClasses;
namespace Program
{
public class TestAnimals
{
// prints the following:
// Missy: Meowww!
// Mr. Mistoffelees: Meowww!
// Lassie: Arf! Arf!
//
public static void Main(string[] args)
{
var animals = new List
new Cat("Missy"),
new Cat("Mr. Mistoffelees"),
new Dog("Lassie")
};
foreach (var animal in animals) {
Console.WriteLine(animal.Name + ": " + animal.Talk());
}
}
}
}
