After the previous article here for simple example of inheritance, today I have decided to write something similar for interfaces.
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
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:
🙂