An Interface is a completely "abstract class" that is used to group related methods with empty bodies. It is a fundamental part of achieving Abstraction in C#.
By convention, interface names always start with a capital I (like IAnimal, IMoveable). This makes it easy to remember that it is an interface and not a regular class.
To create an interface, use the interface keyword. To access the interface methods, the interface must be "implemented" (kinda like inherited) by another class using the : symbol.
using System;// Interface definition interface IAnimal { void AnimalSound(); // interface method (does not have a body) void Run(); // interface method (does not have a body) }
// Pig "implements" the IAnimal interface class Pig : IAnimal { public void AnimalSound() { // The body of AnimalSound() is provided here Console.WriteLine("The pig says: wee wee"); } public void Run() { // The body of Run() is provided here Console.WriteLine("The pig is running..."); } }
class Program { static void Main(string[] args) { Pig myPig = new Pig(); // Create a Pig object myPig.AnimalSound(); myPig.Run(); } }
new IAnimal() is invalid).public and abstract. You do not need to write these keywords!Why do we need interfaces if we already have Abstract Classes?
The biggest advantage of interfaces is that C# does not support "multiple inheritance" (a class can only inherit from one base class). However, it does allow a class to implement multiple interfaces!
To implement multiple interfaces, separate them with a comma:
using System;interface IFirstInterface { void MyMethod(); // interface method }
interface ISecondInterface { void MyOtherMethod(); // interface method }
// Implementing multiple interfaces using a comma class DemoClass : IFirstInterface, ISecondInterface { public void MyMethod() { Console.WriteLine("Some text..."); } public void MyOtherMethod() { Console.WriteLine("Some other text..."); } }
class Program { static void Main(string[] args) { DemoClass myObj = new DemoClass(); myObj.MyMethod(); myObj.MyOtherMethod(); } }
Can an interface contain fields (variables) in C#?