The purpose of Interfaces in C# is to define a contract. Any class that then implements the interface will know which methods it needs to have. An interface is like an abstract class, but without any implementation.
Let’s look at an example. Let’s say we have a Vehicle interface, like below. A Vehicle will have wheels. If this were an abstract class, we could define the implementation of HowManyWheels, for example. As this is an interface, we are simply saying there is a method HowManyWheels that will need to be implemented:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Carl.Interfaces { interface IVehicle { int wheels { get; set; } int GetWheels(); string HowManyWheels(); } class Program { static void Main(string[] args) { try { IVehicle i = null; i.wheels = 4; Console.WriteLine("Vehicle has {0} wheels", i.GetWheels()); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } Console.ReadLine(); } } }
If we try to run this, we will get an error, as the interface itself cannot be instantiated:
To use the interface, let’s create a new derived class called Car. In Visual Studio, it will tell us which methods need to be implemented:
Now, we can add code implement IVehicle interface with a Car class, and create an instance of the Car class:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Carl.Interfaces { public interface IVehicle { int wheels { get; set; } int GetWheels(); string HowManyWheels(); } public class Car : IVehicle { int IVehicle.wheels { get; set; } int IVehicle.GetWheels() { return 4; } string IVehicle.HowManyWheels() { return string.Format("There are 4 wheels"); } } class Program { static void Main(string[] args) { try { IVehicle ferrari = new Car(); ferrari.wheels = 4; Console.WriteLine("Vehicle has {0} wheels", ferrari.GetWheels()); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } Console.ReadLine(); } } }
Running this:
I AM SPENDING MORE TIME THESE DAYS CREATING YOUTUBE VIDEOS TO HELP PEOPLE LEARN THE MICROSOFT POWER PLATFORM.
IF YOU WOULD LIKE TO SEE HOW I BUILD APPS, OR FIND SOMETHING USEFUL READING MY BLOG, I WOULD REALLY APPRECIATE YOU SUBSCRIBING TO MY YOUTUBE CHANNEL.
THANK YOU, AND LET'S KEEP LEARNING TOGETHER.
CARL