Interfaces
An interface defines a behavioral contract without instance fields or a concrete object layout.
Declaring an interface
Interface members declare signatures without implementation bodies. Methods, properties and indexers can participate in a contract.
interface IRenderable
{
void Render();
readonly bool Visible { get; }
readonly int this[int index] { get; }
}
Interface members are public contract members. A readonly member can be called through a readonly interface reference.
Implementing an interface
Add the interface to a struct's base list and provide compatible public instance members for the complete contract.
struct Sprite : IRenderable
{
private bool visible;
public Sprite(bool isVisible)
{
visible = isVisible;
}
public void Render()
{
DrawSprite();
}
public readonly bool Visible
{
get { return visible; }
}
public readonly int this[int index]
{
get { return index; }
}
}
Interface references
A struct value converts to an interface value, and a struct reference converts to an interface reference. The interface representation preserves the concrete object and its dispatch information. Calls are routed to the implementation belonging to the runtime struct.
Sprite sprite = Sprite(true);
IRenderable& renderable = sprite;
renderable.Render();
bool visible = renderable.Visible;
An interface pointer type such as IRenderable* may be used directly, but a raw Sprite* is not implicitly converted to it. Form an interface value or reference before working through the interface contract.
Interface inheritance
An interface may extend multiple other interfaces. Its contract includes all inherited members together with its own declarations.
interface IUpdatable
{
void Update();
}
interface IEntity : IRenderable, IUpdatable
{
int GetId();
}
A struct may implement several interfaces while also extending one base struct.