Interface
An interface holds definitions for a group of related functionalities which can be implemented by a struct or class.
This polymorphism tool allows for usage like exploiting behavior from multiple sources within a single class. Interfaces prove critical in C#, which does not allow multiple inheritance, or allow structs to inherit. A class can only implement an interface once, but it can inherit one multiple times via base classes. A base class can implement interface members through virtual members; furthermore, it can alter interface behavior through overrides.
Properties and indexers can employ extra accessors using properties and indexers defined in an interface. Interfaces can implement other interfaces.
Use the interface keyword to define an interface. Review the example below:
interface IInterface { bool Equals(T obj); }
Review an example of interface use below:
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System;
namespace InterfaceAPP
{
public interface IShipping
{
// members of the interface
void showTransfer();
int getQuantity();
}
public class Shipping : IShipping
{
private string sCode;
private string date;
private int quantity;
public Shipping()
{
sCode = " ";
date = " ";
quantity = 0;
}
public Shipping(string c, string d, int q)
{
sCode = c;
date = d;
quantity = q;
}
public int getQuantity()
{
return quantity;
}
public void showTransfer()
{
Console.WriteLine("Transfer: {0}", sCode);
Console.WriteLine("Date: {0}", date);
Console.WriteLine("Quantity: {0}", getQuantity());
}
}
class Test
{
static void Main(string[] args)
{
Shipping s1 = new Shipping("6544", "6/12/2080", 75900);
Shipping s2 = new Shipping("5457", "9/09/2080", 422900);
s1.showTransfer();
s2.showTransfer();
Console.ReadKey();
}
}
}
Interfaces can contain properties, methods, indexers, events, and any combination of these four. They cannot contain operators, constants, fields, destructors, types, or instance destructors. Interfaces, by default, are public. They also cannot contain static members.
In implementation, members must have a corresponding interface member declared public, non-static, and bearing the same name and signature. In a class or struct, an implementation must exist for all members defined by the interface. Classes and structs do not receive functionality from an interface in a way resembling an inherited base class; however, when a base class implements an interface, all classes inheriting it use that implementation.