C# Interfaces

Similar to Abstract classes, Interfaces work as a template for other classes to inherit from in order to guarantee that certain variables will exist in every derived class.

Vincent Taylor
2 min readSep 4, 2021
A C# Interface

Interfaces do now allow any implementations in themselves. They only allow the definition of methods, while the implementation is written in the derived classes.

Interfaces are also only allowed to use Property variables (variables with user-defined getters and setters).

Interface names, in common coding practice, are usually started with an “I” at the beginning to indicate clearly that it is an Interface, not a class. E.g. “IDestructable”, “ICharacter”, “IMovementSystem”, etc.

Derived class 1
Derived class 2

Each derived class must include the implementation for any Methods in the Interface, plus any Properties in the Interface.

Each derived class may implement the Methods or Properties differently, but they must all be implemented.

Multiple inheritance of Interfaces

Another great feature to using Interfaces is that you can find derived components by their Interfaces, when you don’t necessarily know which derived component is there.

Example:

Imagine you have bullets in your game. The bullets do damage to both the Player and enemies if they hit them.

The “Player” script inherits from “IDestructable” and “IPlayerControlled”.

The “Enemy” script inherits from “IDestructable” and some other Interfaces.

When the bullet hits a GameObject, rather than checking if “Player” is on it, or if “Enemy” is on it, you can simply check if “IDestructable” is on it.

This also has the benefit of making both the “Player” and “Enemy” classes have a public “Damage(int amount)” Method.

A very useful feature of C# which can dramatically increase code cleanliness and efficiency.

--

--

Vincent Taylor

Unity game developer / C# Programmer / Gamer. Australian (Tasmanian) indie games developer for 10+ years. Currently looking for games industry employment.