DEFAULT INTERFACE
The default interface implementation (default interface implementation) in C# is a feature introduced starting with C# 8.0. This feature allows you to provide default implementations for methods within interfaces, thus reducing the need to modify all classes that implement an interface when a new method is added. The following is a detailed description of how to use this feature.
1. Defining an interface with a default implementation
In C#, an interface can now contain methods with method bodies, providing a default implementation that can be used by the classes that implement the interface. Here is an example of an interface with a method body with a default implementation:
public interface IExample
{
// Metodo con implementazione predefinita
void DefaultMethod()
{
Console.WriteLine(“This is a default implementation.“);
}
// Metodo senza implementazione predefinita
void AbstractMethod();
}
2. Implementation of an interface in a class
When a class implements an interface with predefined methods, you do not need to provide an implementation for those methods unless you want to override them. Here is an example:
public class ExampleClass : IExample
{
// Implementazione obbligatoria del metodo astratto
public void AbstractMethod()
{
Console.WriteLine(“Implementation of abstract method.“);
}
// Metodo DefaultMethod può essere sovrascritto, ma non è obbligatorio
// Se non viene sovrascritto, verrà utilizzata l’implementazione predefinita dell’interfaccia
}
3. Using the methods of the interface
When using a class that implements the interface, methods with default implementations can be called like any other method:
class Program
{
static void Main(string[] args)
{
IExample example = new ExampleClass();
// Chiamata al metodo astratto implementato nella classe
example.AbstractMethod();
// Chiamata al metodo con implementazione predefinita
example.DefaultMethod();
}
}
4. Overriding a default method
If you want to provide your own implementation of a default method, you can do so in the class:
public class CustomExampleClass : IExample
{
public void AbstractMethod()
{
Console.WriteLine(“Implementation of abstract method.“);
}
// Sovrascrittura del metodo con implementazione predefinita
public void DefaultMethod()
{
Console.WriteLine(“This is a custom implementation.“);
}
}
Leave A Comment