C#

Interface in C# explained with Unity examples

ยท 1 min read
Interface in C# explained with Unity examples

Interface is another cornerstone concept in the Object-oriented Programming. They are not classes so that they can't have their own instances.


Features of interface:

  • A class can implement more than one interfaces
  • All methods and property (or member variables) must be implemented
  • An interface can inherit from another interface
  • Interface is a great way of organizing the code and classes that allows different classes to share similar functions
  • Interface can only have abstract methods and properties, we can understand the interface is a completely abstract class
  • Interface can contain either properties or methods. Same as the other programming languages such as Swift, Java is a bit different

Example of interface:


By convention, interfaces starts with a capital I followed by a name, also the name is preferred to use something like -able to describe its function.

using UnityEngine;
using System.Collections;

//This is a basic interface with a single required method.
public interface IDestroyable {
	 void Destroy();
}

//This is a generic interface where T is a placeholder
//for a data type that will be provided by the 
//implementing class.
public interface IPurchasable<T> {
  void Purchase(T price);
}

// interface on property
public interface ICar {
    int Year { get; set; }
}

When a class implements a interface, it must implement all the methods of that interface:

using UnityEngine;
using System.Collections;

public class Car: MonoBehaviour, IPurchasable<float> , IDestroyable, ICar {
  //The required method of the IKillable interface
  public void Destroy() {
    //Do something fun
  }

  //The required method of the IPurchasable interface
  public void Purchase(float price) {
    //Do something fun
  }

  // automatically implemented
  public int Year { get; set; }
}