C# – simple example of interfaces

After the previous article here for simple example of inheritance, today I have decided to write something similar for interfaces.

Info

Pretty much, interfaces are something similar that objects implement. 🙂 E.g., if you have keyboard and a phone, they both have different buttons. Thus, you may ask for Info() and they would give you some information about the  key. Or you may ask to see how they Multiply a number and the results would be different. Even they both can go in a list of objects, that implement this interface <INumberOfButtons>. Pretty much the following:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


class Program
{
    static void Main()
    {
        Keyboard objKeyboard = new Keyboard();
        OldPhone objOldPhone = new OldPhone();
        objKeyboard.Info();
        objOldPhone.Info();

        List <INumberOfButtons> lstMyList = new List<INumberOfButtons>();
        lstMyList.Add(objKeyboard);
        lstMyList.Add(objOldPhone);

        foreach (var item in lstMyList)
        {
            item.Multiply(5);
        }
    }
}

class Keyboard : INumberOfButtons
{
    public void Info()
    {
        Console.WriteLine("I am a keyboard and I have plenty of keys!");
    }

    public void Multiply(int value)
    {
        Console.WriteLine(value*5);
    }

    public void NotImplemented()
    {
        throw new NotImplementedException();
    }
}

class OldPhone : INumberOfButtons
{
    public void Info()
    {
        Console.WriteLine("I am a phone and I have 10 keys.");
    }

    public void Multiply(int value)
    {
        Console.WriteLine(value * value * value);
    }

    public void NotImplemented()
    {
        throw new NotImplementedException();
    }
}

interface INumberOfButtons
{
    void Info();
    void Multiply(int value);
    void NotImplemented();
}

This is what you get:

Info01

🙂