C# Interfaces

Leave a comment

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:

 

ABOUT CARL DE SOUZA

Carl de Souza is a developer and architect focusing on Microsoft Dynamics 365, BI, Web, Cloud and Data Science.

carldesouza.comLinkedIn Twitter | YouTube

 

See more articles on: C#

Leave a Reply

Your email address will not be published. Required fields are marked *