An interface is a class model. It contains methods and properties, with the particularity that it does not provide the implementation of methods. This means that we just describe the methods without describing what they do.
An interface is useless on its own: each interface is doomed to be implemented by a class (or a structure) which will have to implement its methods and have its properties. The purpose of an interface is to define the methods and properties offered by any class (or structure) that implements it, without the developer needing to know how they are coded. To put it simply, an interface is like a contract: it defines expectations without planning the technical solutions that will be used.
Example 1:
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 | using System; using System.Collections.Generic; namespace Interfaces { class Program { static void Main(string[] args) { List<Dog> dogs = new List<Dog>(); dogs.Add(new Dog("Fido")); dogs.Add(new Dog("Bob")); dogs.Add(new Dog("Adam")); dogs.Sort(); foreach(Dog dog in dogs) Console.WriteLine(dog.Describe()); Console.ReadKey(); } } interface IAnimal { string Describe(); string Name { get; set; } } class Dog : IAnimal, IComparable { private string name; public Dog(string name) { this.Name = name; } public string Describe() { return "Hello, I'm a dog and my name is " + this.Name; } public int CompareTo(object obj) { if(obj is IAnimal) return this.Name.CompareTo((obj as IAnimal).Name); return 0; } public string Name { get { return name; } set { name = value; } } } } |
Example 2:
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 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 | // C# program to illustrate the interface using System; // interface declaration interface Vehicle { // all are the abstract methods. void changeGear(int a); void speedUp(int a); void applyBrakes(int a); } // class implements interface class Bicycle : Vehicle{ int speed; int gear; // to change gear public void changeGear(int newGear) { gear = newGear; } // to increase speed public void speedUp(int increment) { speed = speed + increment; } // to decrease speed public void applyBrakes(int decrement) { speed = speed - decrement; } public void printStates() { Console.WriteLine("speed: " + speed + " gear: " + gear); } } // class implements interface class Bike : Vehicle { int speed; int gear; // to change gear public void changeGear(int newGear) { gear = newGear; } // to increase speed public void speedUp(int increment) { speed = speed + increment; } // to decrease speed public void applyBrakes(int decrement){ speed = speed - decrement; } public void printStates() { Console.WriteLine("speed: " + speed + " gear: " + gear); } } class Example2{ // Main Method public static void Main(String []args) { // creating an instance of Bicycle // doing some operations Bicycle bicycle = new Bicycle(); bicycle.changeGear(2); bicycle.speedUp(3); bicycle.applyBrakes(1); Console.WriteLine("Bicycle present state :"); bicycle.printStates(); // creating instance of bike. Bike bike = new Bike(); bike.changeGear(1); bike.speedUp(4); bike.applyBrakes(3); Console.WriteLine("Bike present state :"); bike.printStates(); } } |
Create an interface
The declaration of an interface is similar to that of a class, with a few differences. In particular, we use the interface keyword instead of the class keyword.
In terms of accessibility, an interface is always public, so you cannot use an access restrictor (public, private, protected or internal)
Here is an example interface:
1 2 3 4 5 6 7 | interface IAnimal { string Name { get; } void Move(); } |
Thanks to this, we know that an object stored in the form of IAnimal will always have the Name property accessible for reading and the Move method.
You just have to put get; and not get {return m_name; } because the interface does not know m_name and does not care. Again, what matters are the features available, not how they are coded. Besides, who told you that the developer would name a field with m_ in front of it and not just _ as some do?
Use an existing interface
Any class implementing an interface must implement its methods (with the same signatures) and its properties. In case you forgot, signing a method identifies it; it depends on three things: its name, its return type and its arguments.
Let’s go back to the previous example. The implementation of Move must therefore also be named Move, return void, and take no parameter as input.
Here is an example :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | class Dog : IAnimal { private string m_name; // On implémente la propriété Name accessible en lecture. public string Name { get { return m_name; } } public Dog(string name) { m_name = name; } // On implémente la méthode Move. public void Move() { Console.WriteLine("{0} bouge.", m_name); } } |
You can manipulate objects with the type of the interface: you don’t have to use the type of a class that implements it; you can therefore put in the Main
:
1 2 3 4 | IAnimal milou = new Dog("Milou"); milou.Move(); |
And it will display Snowy moves.in console.
As you can see, it is possible to store an object of type Dog
in another of type IAnimal
, since it Dog
implements the interface IAnimal
.
Use multiple interfaces
Depending on your needs, you can even use multiple interfaces. To do this, you have to separate the interfaces with commas, as in the following example (where SampleClass
implements both IControl
and ISurface
):
1 2 3 4 5 6 | class SampleClass : IControl, ISurface { // Code de la classe } |
In this case, if both interfaces describe a method with the same signature, they will both call the same method. See instead:
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 | interface IControl { void Paint(); } interface ISurface { void Paint(); } class SampleClass : IControl, ISurface { public void Paint() { // Implémentation de Paint } } class Program { static void Main(string[] args) { // Appel de Paint depuis IControl IControl myControl = new SampleClass(); myControl.Paint(); // Appel de Paint depuis ISurface ISurface mySurface = new SampleClass(); mySurface.Paint(); } } |
In both cases, the same method Paint
is called. To do two different methods, replace the code SampleClass
with:
1 2 3 4 5 6 7 8 9 10 11 12 13 | class SampleClass : IControl, ISurface { void IControl.Paint() { // Implémentation du Paint appelé par un objet IControl } void ISurface.Paint() { // Implémentation du Paint appelé par un objet ISurface } } |
You notice in passing that I did not put an accessor in front of the two methods although I had put one public
earlier. Since this time these are methods that each implement a specific interface, they are necessarily public because they can only be used from interfaces.
You can then do:
1 2 3 4 5 6 7 8 9 10 11 12 13 | SampleClass obj = new SampleClass(); // La conversion se fait automatiquement. IControl c = obj; // Appelle la méthode IControl.Paint de SampleClass. c.Paint(); // Là-aussi, la conversion se fait automatiquement. ISurface s = obj; // Appelle la méthode ISurface.Paint de SampleClass. s.Paint(); |
1 2 3 | obj.Paint(); |
would produce a compilation error because we did not create a “general” method Paint
. It is however doable if we implement a Paint
“general”:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | class SampleClass : IControl, ISurface { // Là je peux mettre public public void Paint() { // Implémentation du Paint appelé par un objet SampleClass // (ou d'une interface qui n'a pas d'implémentation spécialement pour elle) } void IControl.Paint() { // Implémentation du Paint appelé par un objet IControl } void ISurface.Paint() { // Implémentation du Paint appelé par un objet ISurface } } |
In this case, c.Paint();
call again IControl.Paint
and do not call the “general” method precisely because we have made a method specially for the interface.
At the moment you probably do not see all the usefulness of interfaces; but by working on real projects you may have the opportunity to use them. Anyway, in this tutorial we will need it, although you won’t necessarily see a lot of it right away.
Source:
https://openclassrooms.com/fr/courses/218202-apprenez-a-programmer-en-c-sur-net/217900-les-interfaces
https://www.geeksforgeeks.org/c-sharp-interface/