INTERFACE

C sharpC sharp interfaces are like reference types classes. Interfaces are similar to abstract classes that is, they contain the definition of methods, properties and other members that are not implemented. C# does not support multiple inheritance like other languages such as Pyton, C++ but only one class can be derived. However, the language allows us to implement multiple interfaces.

IMPLEMENT AN INTERFACE

But what does it mean to implement an interface? A class that claims to implement an interface is required to implement all the members, properties, methods and events that have been defined in it. It is as if a sort of contract is established between the class that implements the interface and the interface itself. The interfaces support multiple inheritance. You can get a reference to the interface starting from the class that implements it using the as operator.

DECLARE AN INTERFACE

using System;
namespace Interface
{
        class Program
        {
            static void Main(string[] args)
            {
        
            }
        }
        public interface IMyInterface1
        {
            void MyMethod1();
            string MyProperty1 {get;set;}
        }
        public interface IMyInterface2
        {
            void MyMethod2();
            string MyProperty2 {get;set;}
        }
        public class MyClassA : IMyInterface1
        {
            public void MyMethod1()
            {
                Console.WriteLine("Sto implmentando MyMethod1() dell'interfaccia IMyInteface1.");
            }
            public string MyProperty1{get;set;}
        }
        public class MyClassB
        {
            public void MyMethod()
            {
                Console.WriteLine("Sto eseguendo MyMethod() di MyClassB.");
            }
        }
    }

As you can see, the declaration of an interface in c sharp is similar to the declaration of a class only that instead of the keyword class we have to put the keyword interface. By convention, an interface name begins with a capital letter I. All members of an interface are by definition public, abstract methods cannot be declared. The class that implements the interface, MyClassA is required to provide a concrete implementation of the members defined in it. A class can derive from a single superclass, and from one or more interfaces, the declaration of the Superclass must be the first, any interface implementations must be separated with commas. Let’s see a code example.

using System;
namespace Interface
{
    class Program
    {
        static void Main(string[] args)
        {
          MyClassA a = new MyClassA();
          a.MyMethod();
          a.MyMethod1();
          a.MyProperty2 = "Corso C#.";
          Console.WriteLine(a.MyProperty2);
        }
    }
    public interface IMyInterface1
    {
        void MyMethod1();
        string MyProperty1 {get;set;}
    }
    public interface IMyInterface2
    {
        void MyMethod2();
        string MyProperty2 {get;set;}
    }
    public class MyClassA : MyClassB, IMyInterface1, IMyInterface2
    {
        public void MyMethod1()
        {
            Console.WriteLine("Sto implmentando MyMethod1() dell'interfaccia IMyInteface1");
        }
        public string MyProperty1{get;set;}

        public void MyMethod2()
        {
            Console.WriteLine("Sto implmentando MyMethod2() dell'interfaccia IMyInteface2.");
        }
        public string MyProperty2{get;set;}
    } 
    public class MyClassB
    {
        public void MyMethod()
        {
            Console.WriteLine("Sto eseguendo MyMethod() di MyClassB.");
        }
    }
}

USE THE INTERFACES

using System;
namespace Interface
{
    class Program
    {
        static void Main(string[] args)
        {
          MyClassA a = new MyClassA();
          IMyInterface i = a as IMyInterface;
          ((MyClassA)i).MyMethod2(); //TO INVOKE THE METHODS BELONGING ONLY 
                                     //TO MyClassA YOU MUST DO THE CASTING.
          MyClassB.MyMethod(i);
        }
    }
    public interface IMyInterface
    {
            void MyMethod();
    }
        
    public class MyClassA : IMyInterface
    {
            public void MyMethod()
            {
                Console.WriteLine("MyMethod() di MyClassA.");
            }
            public void MyMethod2()
            {
                Console.WriteLine("MyMethod2() di MyClassA.");
            }
    }
    public class MyClassB
    {
            public static void MyMethod(IMyInterface myInterface)
            {
                myInterface.MyMethod();
            }
    }  
}

We said that you can get a reference to the interfaces starting from the classes that implement it. This can be done as MyClassA implements the IMyInterface interface. Another important implication allows us to strongly decouple the classes in the code, in this case MyClassB does not contain references to MyClassA as the interface is used as a method parameter.

ABSTRACT CLASSES IN BRIEF

At this point a question may arise: when to use interfaces and when, instead, to use abstract classes? We said that they both define a contract for the classes they are associated with, since, internally, they contain no implementations, only declarations. Moreover, pure abstract classes provide a “stronger” type of contract, since, in addition to defining the behaviors for the associated classes, they also represent their base type

THE INTERFACES IN BRIEF

Otherwise, interfaces allow greater flexibility, as they are independent and transversal types with respect to the class hierarchy defined through inheritance bonds. The use of interfaces is therefore to be preferred in the event that we want to define contracts of a general nature, which can be used independently of the links of inheritance and which do not impose specific and exclusive behaviors. Types such as interfaces and abstract classes, which have a primarily declarative value, are generically identified as abstract types, as opposed to classes that contain actual implementations, which are denoted as concrete types.

MORE ABOUT INTERFACES

In C#, an interface is a contract that defines a group of methods, properties, events or indexers that a class or struct must implement. Interfaces do not contain method implementations (until C# 8.0), only method signatures.

Here are some key points about interfaces in C#:

1. Defining an interface:

Interfaces are defined using the interface keyword. Here is an example of how to define an interface:

public interface IVehicle
{
   void StartEngine();
   void StopEngine();
   int Wheels { get; }
}

2. Implementation of an interface:

A class that implements an interface must provide the implementation for all members of the interface. Here is an example:

public class Car : IVehicle
{
     public int Wheels { get; private set; }

     public Car()
     {
       Wheels = 4;
     }

     public void StartEngine()
     {
       Console.WriteLine(“Engine started“);
     }

     public void StopEngine()
     {
       Console.WriteLine(“Engine stopped“);
     }
}

3. Inheritance of interfaces:

An interface can inherit from one or more interfaces. Here is an example:

public interface IElectricVehicle : IVehicle
{
     void ChargeBattery();
}

4. Use of interfaces:

Interfaces are often used for dependency and dependency injection, object-oriented programming and polymorphism. Here is an example of how to use an interface:

public class Garage
{
    private IVehicle _vehicle;

    public Garage(IVehicle vehicle)
    {
       _vehicle = vehicle;
    }

    public void ServiceVehicle()
    {
         _vehicle.StartEngine();
         // Perform service
         _vehicle.StopEngine();
    }
}

IVehicle myCar = new Car();
Garage myGarage = new Garage(myCar);
myGarage.ServiceVehicle();

LINKS TO PREVIOUS POST

LINK TO THE CODE ON GITHUB