Are we able to implement a method inside an interface?
I think the answer was no!
But was before C# 8, the definition of an interface is a class (with the key interface instead of class) that consist on representing a contract between an object and its user. Interfaces can include methods, properties, indexers, and events as members. But, we have ONLY declarations of all of these and not implementations! To do that, we use abstract classes with abstract methods and operations.
We consider this an old definition because, in C# 8, we are able to implement a method in an interface
This new features was introduced in C# 8 that was launched in DotNetConf 2019 on 23 September.
We will start by creating a console application, and add an interface and a class that inherit from this interface.
We will add four operations inside the interface to see some possible cases.
interface InterfaceA
{
void OperationA();
void OperationB(string message);void OperationC(string message)
{
Console.WriteLine(message);
}void OperationD(string message) => OperationB(message);
So, OperationA and OperationB aren’t implement otherwise OperationC and OperationD include implementation.
OperationD call OperationB as implementation.
Now, we will implement the class by the interface:
public class MyClass : InterfaceA
{
public void OperationA()
{
Console.WriteLine(“This is implemented inside the class!”);
}public void OperationB(string message)
{
Console.WriteLine(message);
}
}
And we will call our operation in main class in this way:
class Program
{
static void Main(string[] args)
{
CallClass();
Console.ReadLine();
}public static void CallClass()
{
InterfaceA myClass = new MyClass();
myClass.OperationA();
myClass.OperationB(“This is implemented in OperationB”);
myClass.OperationC(“This is implemented inside the interface.”);
myClass.OperationD(“this is inside the interface”);
}
}
And this is the result:
Source code on GitHub: https://github.com/didourebai/MicroserviceSwaggerApis/tree/master/source/repos/ExampleCSharp8