C# Intro to the Interface
Tags: beginners, interface, unity3d, csharp
Published: 2019-07-11 02:11:58

---
title:C# Intro to the Interface
published: true
description: 
tags: beginner, Interface, Unity,CSharp
---
#Prelude 
          
Just so you know I'm not an Interface wizard who knows every nook and cranny that exists with an interface. I am just gonna explain how one can effectively use an interface and make their day/code less cumbersome and a lot cleaner. Also, a few elements of the examples will have some unity keywords in it, But that will not bog you from learning the fundamental concept that I'm trying to explain. Without further ado, let's jump into the topic. 

# What is an Interface?
<p>
An interface is a base class with a bunch of method declarations with no definitions, This interface class cannot work on its own as all its methods are just declarations. It will expect some other class to inherit this interface and upon inheriting the interface will make it mandatory to the inherited class to define all the method declarations inside it. In essence, an interface tells a class about the methods it needs to have in order for the class to perform certain functions but the interface will not tell what the function does, It will expect the writer of that class to know it.

<br>

<b> I hope this much is clear, let's continue with an example ,</b> 
A human will perform a function of eating without which a human will die. If the human were a class we interface the class human with an Interface <b>IEat</b> 
(<I>People always precede <b>Interface</b> with an <b>"I"</b> so let us follow the same rule, It's not necessary but I'd advise everybody to follow the same</I>). 
This
 <b>IEat</b> 
will only add a method to the class <b>Human</b> called <b>Eat</b> and this method will have a parameter called <b>consummate amount</b>. Remember this method or the parameter from the interface does not tell us how to eat or how much to eat. They will only tell these things to exist in class and later the writer of the class should specify how to eat the food and how much/what food to eat <b>Human</b>.
</p>
####This is how the code for the above-mentioned functionality will look like

<b>IEat.cs </b> Interface
```c#
public interface IEat {

    void Eat(int consumateamount);
}
```

<b>Human.cs</b>
```c#
public class Human : IEat
{
    public void Eat(int consumateamount)
    {
        PutItInMouth(GetFood(consumateamount));
    }

    private Food GetFood(int consumateamount)
    {
        Food food = new Food();
        food.apple = consumateamount;
        food.meat = consumateamount;
        return food;
    }

    public void PutItInMouth(Food food)
    {
        //Human Eats
    }
 }

public class Food
{
    public int apple;
    public int meat;
}
```
###So now let's see how we could use this <b>Eat(int consumateamount)</b> for a human test subject.
<p>
Let's consider that the human brain has a class called <b>BrainSchedule,</b> Inside the class we have each time cycle of a day as a method and inside every method we call the <b>Eat(int consumateamount)</b> method for an instance of a  human subject. Here the amount of food consumed is determined by the time cycle method. 
</p>
```c#
public class BrainSchedule : MonoBehaviour
{
    private Human myHuman;

    private void Morning()
    {
        myHuman.Eat(2);
    }
    private void Noon()
    {
        myHuman.Eat(4);
    }
    private void Evening()
    {
        myHuman.Eat(1);
    }
    private void Night()
    {
        myHuman.Eat(2);
    }
}
```
<p>
      As you could see the <b>BrainSchedule</b> class assumes that the <b>Human</b> class has an eat method inside it and calls that method at different cycles of the day to keep the human well nourished.
</p>
<br>
<br>
###We've just learned what an <b>Interface</b> is, But this is not the best application of it. 

#Thus we have a make-believe scenario here where  <b>Interface</b> could be used at it's best.
<p>

       Let's say we are maintaining a zoo, and this zoo has a variety of animals. Each animal will have its own base class. We as the zookeepers our main job here is to feed them. Even though each animal has its own unique food preference we can segregate them based on their food habits into three different categories.<b>Herbivores, Carnivores and Omnivores</b></p> 

<b>Writing the feeding system </b>

<p> 
  We will have a common class called Feeding System which allocates the amount of food and feeds it to the respective animals based on the category. The important point to be noted here is each category will have different subcategories. <b>For example,</b> Herbivores eat foods ranging from hay to fruits. Some animals like <b>Koala</b> will eat the only <b>eucalyptus</b>. According to our design, the feeding system will only segregate foods based on the main categories, If Koala does not want to eat berries and only eat eucalyptus then it is up to the Koala to ignore the berries and consume eucalyptus, and will not be spoon-fed by the feeding system. (This in the real life would be a very irresponsible feeding system but for the sake of learning the Interface we are gonna bear with it).
<br>
<br>
Let's define what sort of foods these categories gonna have
<br>
<br>
</p>
```c#
[System.Serializable] //Just so I could view this over the inspector
public class HerbivoreFood
{
    public int hay;
    public int strawberry;
    public int eucalyptus;
}

[System.Serializable]
public class CarnivoreFood
{
    public int salmon;
    public int steak;
    public int lamb;
}

[System.Serializable]
public class OmnivoreFood
{
    public CarnivoreFood carnivoreFood;
    public HerbivoreFood herbivoreFood;
}
```
<p>
Let's create three interfaces based on the three different categories, Each of this category based interfaces will impose one method that takes in the food type of its category type. <b>For example</b>, Iherbivore interface should have an <b>EatGreens</b> method that takes <b>HerbivoreFood</b> instance as an argument. The code sample is provided below 
</p>
```c#
public interface IHerbivore
{

    void EatGreens(HerbivoreFood herbivoreFood);

}
```
```c#
public interface ICarnivore
{
    void EatMeat(CarnivoreFood carnivoreFood);
}
```
```c#
public interface IOmnivore
{
    void EatGreensAndMeat(OmnivoreFood omnivoreFood);
}
```

<p>
And let's create a base class for every animal in the zoo and we will make each animal inherit an interface that suits with their food habits. <b>For example,</b> If an animal likes <b>berries</b>, It will have access to those berries only if the feeding system recognizes that animal is an <b>herbivore</b> and sends it herbivore based food. For the feeding system to recognize a given animal is herbivore or not we need to inherit the base class of an animal from the <b>IHerbivore</b> interface. (If the animal only wants to eat meat then it should inherit from the <b>ICarnivore</b> interface or else if it wants both then it should inherit from the <b>IOmnivore</b> interface.) The code for the base classes are given below.

</p>

```c#
public class Koala : MonoBehaviour, IHerbivore
{
    private int stomach;


    public void EatGreens(HerbivoreFood herbivoreFood)
    {
        EatEucalyptus(herbivoreFood.eucalyptus);
    }

    private void EatEucalyptus(int eucalyptus)
    {
        stomach += eucalyptus;
    }
}
```
<p>
As mentioned earlier due to <b>Koala's</b> inheritance from the <b>IHerbivore</b> class, It will be sent with all of the Herbivore based food but if you look properly at the class you'll realize that after receiving all of the herbivore based food it eats only what it wants to eat which is the <b>eucalyptus</b> and leaves the rest. 
</p>

```c#
public class Panther : MonoBehaviour, ICarnivore
{
    private int stomach;

    public void EatMeat(CarnivoreFood carnivoreFood)
    {
        EatSteak(carnivoreFood.steak);
    }

    private void EatSteak(int steak)
    {
        stomach += steak; 
    }
}
```
<p>
Same way the panther eats only the <b>steak</b> even if it has access to <b>lamb</b> inside the <b>CarnivoreFood</b> Class.
</p>

```c#
public class Bear : MonoBehaviour,IOmnivore
{
    private int stomach;

    public void EatGreensAndMeat(OmnivoreFood omnivoreFood)
    {
        EatBerries(omnivoreFood.herbivoreFood.strawberry);
        EatFish(omnivoreFood.carnivoreFood.salmon);

    }

    private void EatBerries(int berries)
    {
        stomach += berries;
    }

    private void EatFish(int salmon)
    {
        stomach += salmon;

    }
}
```
<p>
And <b>bear</b> as usual being an omnivore eats both <b>berries</b> and <b>salmon</b>.
</p>

<br>
<br>

###Now let's write the feeding system

<p>
The Feeding system should first have access to all the animals in the zoo, So we have all the animals inside the <b>allZooAnimals</b> array which is the type of a <b>GameObject</b>. (It is a <b>Unity</b> specific type don't pay much attention to it, just consider it as a common reference type). So far we have three animals scripts made so we will have three animals in the array and each animal <b>GameObject</b> will have one of the three animal scripts attached to them. As we have all of our animals now we create objects for each food type and initialize it inside the <b>Start()</b> method. After that, we call the <b>FeedAllAnimals()</b> method, which will recognize the type of each animal script attached to each <b>GameObject</b> in the array and call the appropriate method and pass the appropriate food type based on its category.
</p>

```c#
public class FeedingSystem : MonoBehaviour
{

    public GameObject[] allZooAnimals;

    [SerializeField]private HerbivoreFood herbivoreFood;
    [SerializeField]private CarnivoreFood carnivoreFood;
    [SerializeField]private OmnivoreFood omnivoreFood;


    private void Start()
    {
        ///Get food ready
        herbivoreFood = new HerbivoreFood();
        herbivoreFood.hay = 50;
        herbivoreFood.eucalyptus = 50;
        herbivoreFood.strawberry = 100;


        carnivoreFood = new CarnivoreFood();
        carnivoreFood.steak = 60;
        carnivoreFood.salmon = 100;
        carnivoreFood.lamb = 100;

       omnivoreFood = new OmnivoreFood();
        omnivoreFood.herbivoreFood = herbivoreFood;
        omnivoreFood.carnivoreFood = carnivoreFood;

        FeedAllAnimals();
    }


    private void FeedAllAnimals()
    {
        for (int i = 0; i < allZooAnimals.Length; i++)
        {

            IHerbivore herbivore = allZooAnimals[i].GetComponent<IHerbivore>();

            if (herbivore != null)
            {
                herbivore.EatGreens(herbivoreFood);
            }

            ICarnivore carnivore = allZooAnimals[i].GetComponent<ICarnivore>();

            if (carnivore != null)
            {
                carnivore.EatMeat(carnivoreFood);
            }

            IOmnivore omnivore = allZooAnimals[i].GetComponent<IOmnivore>();

            if (omnivore != null)
            {
                omnivore.EatGreensAndMeat(omnivoreFood);
            }
        }
    }
}
```
<p>
The <b>GetComponent </b> inside the <b>FeedAllAnimals()</b> method will get the instance of the animal as the type of the interface, We do this and not the base class of the animals because, the base class might have a hell lot functionalities which the feeding class does not need to know about, By accessing the instance as an interface we know that these methods inside the interface will compulsorily be written inside the class that inherits it, so we can pass the data with confidence also we use this to type check what sort of food that particular instance of the animal eats without having to know anything about that animal apart from its food habit just through the interface. 
</p>

<p>
If you're buying a new animal to the zoo, Fret not! Just add an interface based on their diet to the animal and they will be ready to be fed, <b>For example,</b> see this <b>Tiger</b> and <b>Zebra</b>.
</p>
```c#
public class Tiger : MonoBehaviour, ICarnivore
{
    private int stomach;

    public void EatMeat(CarnivoreFood carnivoreFood)
    {
        EatLamb(carnivoreFood.lamb);
    }

    private void EatLamb(int lamb)
    {
        stomach += lamb;
    }
}
```

```c#
public class Zebra : MonoBehaviour, IHerbivore
{

    private int stomach;

    public void EatGreens(HerbivoreFood herbivoreFood)
    {
        EatHay(herbivoreFood.hay);
        EatBerries(herbivoreFood.strawberry);
    }


    private void EatHay(int hay)
    {
        stomach += hay;
    }

    private void EatBerries(int berries)
    {
        stomach += berries;
    }

}
```

<p> So this marks the end of this tutorial or whatever you call this is, According to me this is the best use of an interface I've seen so far. Maybe there is more to the interface than meets the eye, if you know that is the case lets discuss it in the comments section below. 
<br>
<br>

<i>P.S This is like the first blog that I've ever written in my entire life so if you see places where I could improve both in writing and programming please do let me know, Thanks XOXO </i>
</p>