Note: I have only ever actually used interfaces in java, mostly because I don’t see a need for interfaces when making programs to be used in Unity.
A interface is essentially a completely abstract class. This means all the methods should be abstract. So its a group of related code that a non-abstract class or a struct need to implement. They are used because a class can only inherit one class but it can inherit multiple interfaces, and struct can’t inherit.
You declare a interface by:
interface IInterfaceName<T>
{
returnType MethodName( parameterType1 parameter1);
}
So you use interface instead of class and the name of the Interface should have a Uppercase I at the very beginning. Between the brackets is a abstract method.
You have a class inherit a interface by:
public class ClassName : IInterfaceName<ClassName>
{
}
The class that is implementing the interface must be public, non-static and have the same name as the interface member(the thing between the <>). It must also define all the abstract methods that don’t have a default. It has a default if you define the method in the interface(I believe you need to be working with c# 8.0 and above to do this though), but if you define the method in the class that default will be overridden. If the class that is implementing the interface is abstract it must still define the methods, but you can define them as abstract you just need to essentially tell the compiler that the method is abstract in the class. If a class were to inherit ClassName it would also inherit the interface, although you can still re-implement it. Classes can also define extra indexers and properties(so like get and set methods) for a property or index that is defined in a interface.
One thought on “C# interfaces”
Comments are closed.